summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorBrett Cannon <brett@python.org>2013-05-31 22:11:17 (GMT)
committerBrett Cannon <brett@python.org>2013-05-31 22:11:17 (GMT)
commitb60a43eabf0ee17599caec484f4fe472cb4f36fe (patch)
treeb74fc162f77bdb416cc05cf74542acd6605d3aa6 /Lib
parent028d51236a3e056288c207dd61f780e2ce5f22e1 (diff)
downloadcpython-b60a43eabf0ee17599caec484f4fe472cb4f36fe.zip
cpython-b60a43eabf0ee17599caec484f4fe472cb4f36fe.tar.gz
cpython-b60a43eabf0ee17599caec484f4fe472cb4f36fe.tar.bz2
Add a reset_name argument to importlib.util.module_to_load in order to
control whether to reset the module's __name__ attribute in case a reload is being done.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/importlib/_bootstrap.py14
-rw-r--r--Lib/test/test_importlib/test_util.py12
2 files changed, 25 insertions, 1 deletions
diff --git a/Lib/importlib/_bootstrap.py b/Lib/importlib/_bootstrap.py
index f5b71ba..cd6a263 100644
--- a/Lib/importlib/_bootstrap.py
+++ b/Lib/importlib/_bootstrap.py
@@ -493,8 +493,14 @@ class _ModuleManager:
"""
- def __init__(self, name):
+ def __init__(self, name, *, reset_name=True):
+ """Prepare the context manager.
+
+ The reset_name argument specifies whether to unconditionally reset
+ the __name__ attribute if the module is found to be a reload.
+ """
self._name = name
+ self._reset_name = reset_name
def __enter__(self):
self._module = sys.modules.get(self._name)
@@ -508,6 +514,12 @@ class _ModuleManager:
# (otherwise an optimization shortcut in import.c becomes wrong)
self._module.__initializing__ = True
sys.modules[self._name] = self._module
+ elif self._reset_name:
+ try:
+ self._module.__name__ = self._name
+ except AttributeError:
+ pass
+
return self._module
def __exit__(self, *args):
diff --git a/Lib/test/test_importlib/test_util.py b/Lib/test/test_importlib/test_util.py
index 7646b34..9897def 100644
--- a/Lib/test/test_importlib/test_util.py
+++ b/Lib/test/test_importlib/test_util.py
@@ -55,6 +55,18 @@ class ModuleToLoadTests(unittest.TestCase):
else:
self.fail('importlib.util.module_to_load swallowed an exception')
+ def test_reset_name(self):
+ # If reset_name is true then module.__name__ = name, else leave it be.
+ odd_name = 'not your typical name'
+ created_module = imp.new_module(self.module_name)
+ created_module.__name__ = odd_name
+ sys.modules[self.module_name] = created_module
+ with util.module_to_load(self.module_name) as module:
+ self.assertEqual(module.__name__, self.module_name)
+ created_module.__name__ = odd_name
+ with util.module_to_load(self.module_name, reset_name=False) as module:
+ self.assertEqual(module.__name__, odd_name)
+
class ModuleForLoaderTests(unittest.TestCase):