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?

web dunia
  • 9,381
  • 18
  • 52
  • 64
99lives
  • 798
  • 1
  • 8
  • 17

2 Answers2

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.

Community
  • 1
  • 1
kjaquier
  • 824
  • 4
  • 11
0

With traceback module:

import traceback

class MyClass():
    def __init__(self):
       file,line,w1,w2 = traceback.extract_stack()[1]
       print(w1)
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219