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

Johannes Janssen mail at johannes-janssen.de
Mon Aug 10 23:51:59 CEST 2009


Christian Heimes schrieb:
> Johannes Janssen wrote:
>>  > class A(object):
>>  >     def __init__(self, mod=__name__):
>>  >         self.mod = mod
>>
>> .... won't work. In this case mod would always be "foo".
>
> You have to inspect the stack in order to get the module of the 
> caller. The implementation of warnings.warn() gives you some examples 
> how to get the module name.
>
> Christian
>
Thanks for the quick and very helpful reply. Basically just copying from 
warnings.warn(), I came up with this:

import sys

class A(object):
    def __init__(self, mod=None):
        if mod is None:
            self.mod = sys._getframe(1).f_globals['__name__']
        else:
            self.mod = mod

In warnings.warn() they used try around sys._getframe(1). As far as I 
understand what is done in warnings, there it is not sure what object 
caused the warning and therefore it is not sure whether you can or 
cannot use sys._getframe(1). Though in my case it should be quite clear. 
Can I be sure that my code will always work?

Johannes



More information about the Python-list mailing list