99lives 99lives - 1 year ago 94
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):


from mymodule import MyClass

instance = MyClass()

should print:


or something like that.

Is this possible?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download