Fix squelch repeated log messages to work with modules loaded via
[pyutils.git] / src / pyutils / function_utils.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2023, Scott Gasch
4
5 """Helper methods dealing with functions."""
6
7 from typing import Callable
8
9
10 def function_identifier(f: Callable) -> str:
11     """
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`.
18
19     Args:
20         f: a Callable
21
22     Returns:
23         A unique identifier for that callable in the format
24         module:function that avoids the pseudo-module '__main__'
25
26     >>> function_identifier(function_identifier)
27     'function_utils:function_identifier'
28
29     """
30
31     if f.__module__ == "__main__":
32         from pathlib import Path
33
34         import __main__
35
36         module = __main__.__file__
37         module = Path(module).stem
38         return f"{module}:{f.__name__}"
39     else:
40         return f"{f.__module__}:{f.__name__}"
41
42
43 if __name__ == "__main__":
44     import doctest
45
46     doctest.testmod()