Creates a function_utils and pull a function_identifer method into
[python_utils.git] / function_utils.py
1 #!/usr/bin/env python3
2
3 from typing import Callable
4
5
6 def function_identifier(f: Callable) -> str:
7     """
8     Given a callable function, return a string that identifies it.
9     Usually that string is just __module__:__name__ but there's a
10     corner case: when __module__ is __main__ (i.e. the callable is
11     defined in the same module as __main__).  In this case,
12     f.__module__ returns "__main__" instead of the file that it is
13     defined in.  Work around this using pathlib.Path (see below).
14
15     >>> function_identifier(function_identifier)
16     'function_utils:function_identifier'
17
18     """
19     if f.__module__ == '__main__':
20         from pathlib import Path
21         import __main__
22         module = __main__.__file__
23         module = Path(module).stem
24         return f'{module}:{f.__name__}'
25     else:
26         return f'{f.__module__}:{f.__name__}'