How to find out in which module an instance of a class is created?

Johannes Janssen mail at
Mon Aug 10 00:06:44 CEST 2009

I like to know in which module an instance of a class was initialized. 
Using __module__ or __name__ within a class only gives me the module in 
which the class was defined not the instance of the class. Is there some 
(simple) way to do this?
For better understanding I'll give an example how I want to use this. 
Okay let's say I've got a module *foo,* in which class A is defined as 
the following:

 > class A(object):
 >     def __init__(self, mod):
 >         self.mod = mod

In a module called *bar* I do the following:

 > import foo
 > a = A(__name__)

Then a.mod should be "bar". But I don't like to pass the value of a.mod 
manually rather than having it default to the module the instance a of A 
was created in (here "bar").
Unfortunately something like this ...

 > class A(object):
 >     def __init__(self, mod=__name__):
 >         self.mod = mod

... won't work. In this case mod would always be "foo".

Kind regards

More information about the Python-list mailing list