Used isort to sort imports. Also added to the git pre-commit hook.
[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
22         import __main__
23
24         module = __main__.__file__
25         module = Path(module).stem
26         return f'{module}:{f.__name__}'
27     else:
28         return f'{f.__module__}:{f.__name__}'