Easier and more self documenting patterns for loading/saving Persistent
[python_utils.git] / function_utils.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """Helper methods dealing with functions."""
6
7 from typing import Callable
8
9
10 def function_identifier(f: Callable) -> str:
11     """
12     Given a callable function, return a string that identifies it.
13     Usually that string is just __module__:__name__ but there's a
14     corner case: when __module__ is __main__ (i.e. the callable is
15     defined in the same module as __main__).  In this case,
16     f.__module__ returns "__main__" instead of the file that it is
17     defined in.  Work around this using pathlib.Path (see below).
18
19     >>> function_identifier(function_identifier)
20     'function_utils:function_identifier'
21     """
22
23     if f.__module__ == '__main__':
24         from pathlib import Path
25
26         import __main__
27
28         module = __main__.__file__
29         module = Path(module).stem
30         return f'{module}:{f.__name__}'
31     else:
32         return f'{f.__module__}:{f.__name__}'