caller_name

privex.helpers.black_magic.caller_name(skip=2) → Optional[str][source]

Get the fully qualified name of a caller in the format some.module.SomeClass.method

Attention

While class instance methods will be returned correctly, class static methods will not show up as expected. The static method some.module.SomeClass.some_static would be returned as some.module.some_static, as if it were a top-level function in the module.

Original source: https://stackoverflow.com/a/9812105

Basic Example

When used within the main program (the script you run python3 xxx.py on), the module will be reported as __main__.

File hello.py:

>>> from privex.helpers.black_magic import caller_name
>>>
>>> def f2():
...     return caller_name()
>>>
>>> def f1():
...     return f2()
...
>>> print(f"[{__name__}] f1 result: {f1()}")
[__main__] f1 result: __main__.f1

However, as we can see below, when we create and run world.py which imports hello.py, it correctly returns the path hello.f1.

File world.py:

>>> from hello import f1
>>>
>>> print(f"[{__name__}] f1 result: {f1()}")
[hello] f1 result: hello.f1
[__main__] f1 result: hello.f1

More Complex Example

File some/module/hello.py:

>>> from privex.helpers.black_magic import caller_name
>>>
>>> class SomeClass:
>>>     def example_method(self, skip=2):
...         return caller_name(skip)
...

File some/module/world.py:

>>> from some.module.hello import SomeClass
>>>
>>> class OtherClass:
...     def call_some(self, skip=2):
...         return SomeClass().example_method(skip)
...

File test.py:

>>> from some.module.hello import SomeClass
>>> from some.module.world import OtherClass
>>>
>>> def main_func():
...     print('SomeClass (2)', SomeClass().example_method())
...     print('OtherClass (1)', OtherClass().call_some(1))
...     print('OtherClass (2)', OtherClass().call_some())
...     print('OtherClass (3)', OtherClass().call_some(3))
...
>>> main_func()
SomeClass (2) test.main_func
OtherClass (1) some.module.hello.SomeClass.example_method
OtherClass (2) some.module.world.OtherClass.call_some
OtherClass (3) test.main_func
Parameters

skip (int) – Specifies how many levels of stack to skip while getting caller name. skip=1 means “who called caller_name”, skip=2 means “who called this function/method” etc.

Return str caller

A fully qualified module path, e.g. some.module.SomeClass.some_method None is returned if skipped levels exceed stack height.