[Python-Dev] Built-in sub modules

Albert Zeyer albzey at googlemail.com
Tue Jun 12 05:17:53 CEST 2012


Hi,

I just created some code to support built-in sub modules.

The naive way I tried first was just to add {"Mod.Sub1.Sub2",
init_modsub1sub2} to _PyImport_Inittab. This didn't worked. Maybe it
would be a nice addition so that this works.

Mod itself, in my case, was a package directory with pure Python code.
Mod.Sub1 also. Only Mod.Sub1.Sub2 was some native code.

Now, to make it work, I added {"Mod", init_modwrapper} to
_PyImport_Inittab. init_modwrapper then first loads the package just
in the way it would have been loaded before (I copied some code from
Python/import.c). Then, in addition, it preloads Mod.Sub1 and call the
native Mod.Sub1.Sub2 initialization (this also needs some
_Py_PackageContext handling) and setups everything as needed.

An example implementation is here:
https://github.com/albertz/python-embedded/blob/master/pycryptoutils/cryptomodule.c
https://github.com/albertz/python-embedded/blob/master/pyimportconfig.c

Maybe this is useful for someone.

I also searched a bit around and I didn't directly found any easier
way to do this. Only a post from 2009
(http://mail.python.org/pipermail/cplusplus-sig/2009-January/014178.html)
which seems like a much more ugly hack.

Btw., my example implementation is part of another Python embedded
project (https://github.com/albertz/python-embedded/). It builds a
single static library with Python and PyCrypto - no external
dependencies. So far, some basic test with RSA/AES works fine. Maybe
that is also interesting to someone.

Regards,
Albert


More information about the Python-Dev mailing list