[Python-Dev] __module__ of newly-created extension classes

David Abrahams David Abrahams" <david.abrahams@rcn.com
Thu, 30 May 2002 16:12:37 -0400


From: "Guido van Rossum" <guido@python.org>


> > I can work around this problem, but I wonder if it would be a good
> > idea if Python set __name__ automatically during the import of an
> > extension module?  I realize that there are ways to undermine this,
> > e.g. explicitly creating a nested module object.
>
> The __name__ attribute is already set as soon as a module is created.
>
> I think the problem is that the extension's dict is not the "current
> globals dict" as returned by PyEval_GetGlobals().

Ah, thanks. I only did a very quick analysis, and didn't remember the way
it turned out when I looked at this in past years for v1.

> There's no convenient way to make this so, since the "current globals
> dict" is taken from the frame (and I don't want to change that).

Fine, I understand, I think.

> What was your workaround?

If I recall correctly, what I was doing in v1 was to keep track of the
module being initialized in some kind of stack under-the-covers, and to
grab its __name__ attribute.

> I thought that the "correct" way to set __module__ is to use a dotted
> name as the type name (the initializer for tp_name).

You would know. Didn't you write that code?

> Can you do that?

Hmm, I see that you have a property which grabs the __module__ from the
class name...

Since I am invoking the metaclass to create classes, I don't set tp_name
directly, but I could manufacture the right name and pass it to the
metaclass. That requires pretty much the same sort of under-the-covers
collaboration between the code that creates the module and the code that
creates the class. That's OK, but (minor point) it means that my library,
which is meant to be a framework of re-usable components, isn't really as
modular as it should be: you couldn't just use the class generation
facilities in the context of someone else's module creation.

Now I'm wondering if there isn't a better way for Python to get ahold of
the current module's __name__ in this case, if you don't want to change
what PyEval_GetGlobals() does.

-Dave