Skip to content

Commit

Permalink
If a module injects something into sys.modules as a side-effect of
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
brettcannon committed Apr 3, 2012
1 parent 368b4b7 commit 927d874
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Lib/importlib/_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,9 @@ def _find_and_load(name, import_):
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:
Expand Down
13 changes: 13 additions & 0 deletions Lib/importlib/test/import_/test_packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ def test_module_not_package(self):
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
Expand Down

0 comments on commit 927d874

Please sign in to comment.