[Python-Dev] Choosing a best practice solution for Python/extension modules (original) (raw)

Nick Coghlan ncoghlan at gmail.com
Sat Feb 21 00:27:23 CET 2009


Brett Cannon wrote:

But there is another issue with this: the pure Python code will never call the extension code because the globals will be bound to pypickle and not pickle. So if you have something like::

# pypickle def A(): return B() def B(): return -13 # pickle def B(): return 42 # pickle from pypickle import * try: from pickle import * except ImportError: pass If you import pickle and call pickle.A() you will get -13 which is not what you are after.

Ah, you may want to think about that a bit more. There's a reason globals are looked up when they're used rather than when their function is defined. Even in your own example, _B isn't defined at all when you define A.

There is a (real) related problem whereby the Python version will use it's own globals if it actually tries to call any functions during the import, but that's a problem shared by any "overwrite at the end of import" approach to swapping in extension module versions of functions.

With appropriate all definitions in the C extension modules, I don't see anything wrong with Daniel's suggested approach. Note also that with this approach _io.all will give the details of what has been overridden by the extension module, so it even still provides a decent level of introspection support.

Cheers, Nick.

-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia



More information about the Python-Dev mailing list