1

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?

2 Answers 2

0

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.

0

With traceback module:

import traceback

class MyClass():
    def __init__(self):
       file,line,w1,w2 = traceback.extract_stack()[1]
       print(w1)
2
  • this will print __init__ Sep 10, 2016 at 9:42
  • nope, it prints main when running from main.py. Test it you'll see. Sep 10, 2016 at 10:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.