Mixing Python and C classes in a module

John Machin sjmachin at lexicon.net
Tue Oct 9 17:18:38 EDT 2007


On 10/10/2007 12:56 AM, Stefan Arentz wrote:
> Is it possible to mix classes defined in both Python and C in the same
> module? Ideally I would like to be able to do:
> 
>  from some.module import MyPythonClass, MyCClass
> 
> I guess that would mean that this would look like this on disk:
> 
>  some/
>    __init__.py
>    module.py      (contains MyPythonClass)
>    module.so      (contains MyCClass)
> 

Alternative to other suggestions:

Instead of module.so, call it _module.so. Then down the end of module.py:

try:
     from _module import *
except ImportError:
     # either panic or shrug as appropriate

Note: the "shrug" response would be appropriate for the use case where 
"module" contains all necessary functionality, and the 
optionally-present "_module" contains replacement classes/types and/or 
functions that are better in some sense e.g. more memory/CPU efficient.

HTH,
John



More information about the Python-list mailing list