See what Python module instantised a class?
<p>Is it possible in a Python class to see the name (or other identifier) of the class or module that instantises it?</p>

<p>For example:</p>

<pre><code># mymodule.py

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

#main.py

from mymodule import MyClass

instance = MyClass()
</code></pre>

<p>Running <code>main.py</code> should print:</p>

<pre><code>main
</code></pre>

<p>or something like that.</p>

<p>Is this possible?</p>

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

<p>See this question: <a href="http://stackoverflow.com/questions/1095543/get-name-of-calling-functions-module-in-python">Get __name__ of calling function&#39;s module in Python</a>.</p>

python