Finding the module object in Python 3 C extensions

Jon Ribbens jon+usenet at unequivocal.eu
Wed Nov 22 10:02:43 EST 2017


In Python 2, a C extension module's global state was stored in
global variables. This obviously means the state is trivially
accessible to all code in the module.

In Python 3, you are supposed to store the global state in an
allocated memory area instead. For functions defined directly
under the module, it is still trivial to find the state, because
a pointer to the module object is passed as the first parameter
to the function, so you just call PyModule_GetState(self).

However, suppose your module defines a new type, and you define
methods on that type. How do those methods get access to the
module object so that they can access the module state?

Unfortunately neither PEP3121 nor the "Porting Extension Modules
to Python 3" documentation seem to have thought to mention this
presumably extremely common situation.



More information about the Python-list mailing list