[Python-Dev] Choosing a best practice solution for Python/extension modules
Steven Bethard
steven.bethard at gmail.com
Mon Feb 23 20:45:59 CET 2009
On Mon, Feb 23, 2009 at 04:02, Nick Coghlan <ncoghlan at gmail.com> wrote:
> 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
On Mon, Feb 23, 2009 at 11:05 AM, Brett Cannon <brett at python.org> wrote:
> 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.
+1 for something like Nick's code. No one has to know they're mucking
around with sys.modules - they just have to use the
import_python_only() function. (And I haven't seen anything in this
thread that's really any better.)
Steve
--
I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
--- Bucky Katt, Get Fuzzy
More information about the Python-Dev
mailing list