(original) (raw)
On Mon, Feb 23, 2009 at 04:02, Nick Coghlan <ncoghlan@gmail.com> 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.
-Brett
Brett Cannon wrote:It is needed, but it's only really needed in the test suite. The
> 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.
"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 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@gmail.com | Brisbane, Australia
\---------------------------------------------------------------