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

Brett Cannon brett at python.org
Mon Feb 23 20:05:39 CET 2009


On Mon, Feb 23, 2009 at 04:02, Nick Coghlan <ncoghlan at gmail.com> wrote:

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.

Well, neither do I as your proposed approach below is what I do for warnings. But I think you and I, Nick, are more comfortable with mucking with imports than most people. =) I think some people early on in this thread said they didn't like the idea of screwing around with sys.modules. But doing that along with an import * from the extension module is probably the simplest solution.

-Brett

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 importpythononly(modname, *extnames): if not extnames: extnames = (("" + modname),) origmodules = {} if name in sys.modules: origmodules[name] = sys.modules[name] del sys.modules[name] try: for name in extnames: origmodules[name] = sys.modules[name] sys.modules[name] = 0 pymodule = importlib.importmodule(modname) finally: for name, module in origmodules.items(): sys.modules[name] = module return pymodule Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20090223/fbe5bef4/attachment.htm>



More information about the Python-Dev mailing list