[Python-Dev] Choosing a best practice solution for Python/extension modules

Nick Coghlan ncoghlan at gmail.com
Mon Feb 23 13:02:50 CET 2009


Brett Cannon wrote:
> I don't want to move it because this isn't some idea for a new feature
> that may or may not be useful; this isn't an "idea", it's needed.

It is needed, but it's only really needed in the test suite. The
"sys.modules hackery" needed to get a Python-only version using the
existing idiom really isn't that complicated and the associated import
behaviour is perfectly well defined (putting a 0 in sys.modules may
currently be a bit questionable, but I'd prefer to make sure that is
officially supported with the desired effect rather than trying to
define a new idiom for the actual library code for handling optional
optimised extension modules).

So, I'm still not seeing any significant problem with providing a
utility function in test.support that hides that hackery and returns the
pure Python version of the module.

For example, a version that allows any number of extension modules to be
suppressed when importing a module (defaulting to the Foo/_Foo naming):

  import sys
  def import_python_only(mod_name, *ext_names):
    if not ext_names:
        ext_names = (("_" + mod_name),)
    orig_modules = {}
    if name in sys.modules:
      orig_modules[name] = sys.modules[name]
      del sys.modules[name]
    try:
      for name in ext_names:
        orig_modules[name] = sys.modules[name]
        sys.modules[name] = 0
      py_module = importlib.import_module(mod_name)
    finally:
      for name, module in orig_modules.items():
        sys.modules[name] = module
    return py_module

Cheers,
Nick.

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


More information about the Python-Dev mailing list