[Python-Dev] __module__ of newly-created extension classes
Guido van Rossum
guido@python.org
Thu, 30 May 2002 21:20:17 -0400
> > If you can rigorously define "current module" I can propose an API.
>
> A rigorous definition is easy; I can't promise it would always meet
> everyone's expectations:
>
> The "current module" is given by the current formula (PyEval_GetGlobals(),
> etc.) except when loading an extension module, in which case the current
> module is the one most recently created.
If the init function of an extension module calls PyImport_Import() to
import another extension which has to be loaded freshly, does that
mean that after that point the definition current module is left to
that other module, or does it revert to the first extension?
What if an extension imports a Python module which loads an extension
module?
> I'm not sure, but this might be simplifiable to:
>
> the "current module" is the one most recently created.
No, because in a Python function defined in a Python module, when that
function is executing that module is the current module.
A possible implementation could maintain a per-thread global which is
NULL when we're not loading an extension. Py_InitModule() sets this
global to the module it creates. When the import mechanism calls an
extension's initxxx function, it saves the value of this per-thread
global; when the function returns, it restores it from the saved
value. Then there could be a new function Py_GetGlobals() that looks
in this per-thread global, and returns its dict if it is not NULL; if
NULL, it falls back on PyEval_GetGlobals(). (You can't promise to
return the current *module*, because that isn't kept track of; only
the current globals are kept track of on the execution stack.)
--Guido van Rossum (home page: http://www.python.org/~guido/)