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

Guido van Rossum guido@python.org
Thu, 30 May 2002 13:42:07 -0400


> When creating new-style classes from within an extension module, the
> current behavior results in the __module__ attribute being set to the name
> of the Python module which first imports the extension module.
> 
> I recall having a similar problem with my own extension classes in
> Boost.Python v1, but was a little surprised to find that it persists in
> Boost.Python v2, when creating new-style classes. A trivial inspection
> reveals this bit of code in typeobject.c:
> 
>     /* Set __module__ in the dict */
>     if (PyDict_GetItemString(dict, "__module__") == NULL) {
>         tmp = PyEval_GetGlobals();
>         if (tmp != NULL) {
>             tmp = PyDict_GetItemString(tmp, "__name__");
>             if (tmp != NULL) {
>                 if (PyDict_SetItemString(dict, "__module__",
>                              tmp) < 0)
>                     return NULL;
>             }
>         }
>     }
> 
> 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().

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).

What was your workaround?

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

--Guido van Rossum (home page: http://www.python.org/~guido/)