Skip to content

bpo-39336: Allow packages to not let their child modules be set on them #18006

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jan 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Lib/importlib/_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -978,7 +978,12 @@ def _find_and_load_unlocked(name, import_):
if parent:
# Set the module as an attribute on its parent.
parent_module = sys.modules[parent]
setattr(parent_module, name.rpartition('.')[2], module)
child = name.rpartition('.')[2]
try:
setattr(parent_module, child, module)
except AttributeError:
msg = f"Cannot set an attribute on {parent!r} for child module {child!r}"
_warnings.warn(msg, ImportWarning)
return module


Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_import/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
temp_dir, DirsOnSysPath)
from test.support import script_helper
from test.test_importlib.util import uncache
from types import ModuleType


skip_if_dont_write_bytecode = unittest.skipIf(
Expand Down Expand Up @@ -1339,6 +1340,19 @@ def test_circular_from_import(self):
str(cm.exception),
)

def test_unwritable_module(self):
self.addCleanup(unload, "test.test_import.data.unwritable")
self.addCleanup(unload, "test.test_import.data.unwritable.x")

import test.test_import.data.unwritable as unwritable
with self.assertWarns(ImportWarning):
from test.test_import.data.unwritable import x

self.assertNotEqual(type(unwritable), ModuleType)
self.assertEqual(type(x), ModuleType)
with self.assertRaises(AttributeError):
unwritable.x = 42


if __name__ == '__main__':
# Test needs to be a package, so we can do relative imports.
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_import/data/unwritable/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import sys

class MyMod(object):
__slots__ = ['__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__',
'__package__', '__path__', '__spec__']
def __init__(self):
for attr in self.__slots__:
setattr(self, attr, globals()[attr])


sys.modules[__name__] = MyMod()
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Import loaders which publish immutable module objects can now publish immutable packages in addition to individual modules.
Loading