[Python-checkins] cpython: If a module injects something into sys.modules as a side-effect of
brett.cannon
python-checkins at python.org
Tue Apr 3 02:34:27 CEST 2012
http://hg.python.org/cpython/rev/a40cd5976215
changeset: 76081:a40cd5976215
parent: 76072:bac033e488b4
user: Brett Cannon <brett at python.org>
date: Mon Apr 02 20:33:56 2012 -0400
summary:
If a module injects something into sys.modules as a side-effect of
importation, then respect that injection.
Discovered thanks to Lib/xml/parsers/expat.py injecting
xml.parsers.expat.errors and etree now importing that directly as a
module.
files:
Lib/importlib/_bootstrap.py | 3 ++
Lib/importlib/test/import_/test_packages.py | 13 ++++++++++
2 files changed, 16 insertions(+), 0 deletions(-)
diff --git a/Lib/importlib/_bootstrap.py b/Lib/importlib/_bootstrap.py
--- a/Lib/importlib/_bootstrap.py
+++ b/Lib/importlib/_bootstrap.py
@@ -927,6 +927,9 @@
if parent:
if parent not in sys.modules:
import_(parent)
+ # Crazy side-effects!
+ if name in sys.modules:
+ return sys.modules[name]
# Backwards-compatibility; be nicer to skip the dict lookup.
parent_module = sys.modules[parent]
try:
diff --git a/Lib/importlib/test/import_/test_packages.py b/Lib/importlib/test/import_/test_packages.py
--- a/Lib/importlib/test/import_/test_packages.py
+++ b/Lib/importlib/test/import_/test_packages.py
@@ -27,6 +27,19 @@
with self.assertRaises(ImportError):
import_util.import_('sys.no_submodules_here')
+ def test_module_not_package_but_side_effects(self):
+ # If a module injects something into sys.modules as a side-effect, then
+ # pick up on that fact.
+ name = 'mod'
+ subname = name + '.b'
+ def module_injection():
+ sys.modules[subname] = 'total bunk'
+ mock_modules = util.mock_modules('mod',
+ module_code={'mod': module_injection})
+ with mock_modules as mock:
+ with util.import_state(meta_path=[mock]):
+ submodule = import_util.import_(subname)
+
def test_main():
from test.support import run_unittest
--
Repository URL: http://hg.python.org/cpython
More information about the Python-checkins
mailing list