the name of a module in which an instance is created?

Alex Martelli aleax at mail.comcast.net
Wed Nov 23 01:00:54 EST 2005


Steven Bethard <steven.bethard at gmail.com> wrote:
   ...
> Unfortunately, no, this is basically what I currently have.  Instead of
> a.name printing 'test', it should print '__main__'.  I want the name of
> the module in which the *instance* is created, not the name of the 
> module in which the *class* is created.

class metaSB(type):
    def __call__(cls, *a, **t):
        result = super(metaSB, cls)(*a, **t)
        result._insmodnam = sys._getframe(1).f_globals['__name__']
        return result

and set the class's __metaclass__ to metaSB.  Untested code, but the
general idea should work.

You could try to hack this without a custom metaclass, e.g. by trying
sys._getframe in __init__, but that's fragile since the __init__ could
be called by a *subclass* in whatever module...


Alex



More information about the Python-list mailing list