3 """Helper methods dealing with functions."""
5 from typing import Callable
8 def function_identifier(f: Callable) -> str:
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).
17 >>> function_identifier(function_identifier)
18 'function_utils:function_identifier'
21 if f.__module__ == '__main__':
22 from pathlib import Path
26 module = __main__.__file__
27 module = Path(module).stem
28 return f'{module}:{f.__name__}'
30 return f'{f.__module__}:{f.__name__}'