99lives 99lives - 2 months ago 13
Python Question

See what Python module instantised a class?

Is it possible in a Python class to see the name (or other identifier) of the class or module that instantises it?

For example:

# mymodule.py

class MyClass():
def __init__(self):
print(instantised_by)

#main.py

from mymodule import MyClass

instance = MyClass()


Running
main.py
should print:

main


or something like that.

Is this possible?

Answer

You can inspect the stack informations with inspect to get the caller stack from __init__ (remember, it's just a function). From that you can get informations such as the caller function name, module name etc.

See this question: Get __name__ of calling function's module in Python.