3 # © Copyright 2021-2022, Scott Gasch
5 """Helper methods dealing with functions."""
7 from typing import Callable
10 def function_identifier(f: Callable) -> str:
12 Given a named `Callable`, 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`.
23 A unique identifier for that callable in the format
24 module:function that avoids the pseudo-module '__main__'
26 >>> function_identifier(function_identifier)
27 'function_utils:function_identifier'
31 if f.__module__ == '__main__':
32 from pathlib import Path
36 module = __main__.__file__
37 module = Path(module).stem
38 return f'{module}:{f.__name__}'
40 return f'{f.__module__}:{f.__name__}'