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