Skip to content
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

bpo-37521: No longer treat insertion into sys.modules as optional in importlib examples #14723

Merged
merged 2 commits into from
Jul 12, 2019
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
18 changes: 9 additions & 9 deletions Doc/library/importlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1638,15 +1638,16 @@ import, then you should use :func:`importlib.util.find_spec`.
# For illustrative purposes.
name = 'itertools'

spec = importlib.util.find_spec(name)
if spec is None:
print("can't find the itertools module")
if name in sys.modules:
print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is None:
print(f"can't find the {name!r} module")
else:
# If you chose to perform the actual import ...
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Adding the module to sys.modules is optional.
sys.modules[name] = module
spec.loader.exec_module(module)
print(f"{name!r} has been imported")


Importing a source file directly
Expand All @@ -1665,10 +1666,9 @@ To import a Python source file directly, use the following recipe

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Optional; only necessary if you want to be able to import the module
# by name later.
sys.modules[module_name] = module
spec.loader.exec_module(module)



Setting up an importer
Expand Down Expand Up @@ -1740,8 +1740,8 @@ Python 3.6 and newer for other parts of the code).
msg = f'No module named {absolute_name!r}'
raise ModuleNotFoundError(msg, name=absolute_name)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
sys.modules[absolute_name] = module
spec.loader.exec_module(module)
if path is not None:
setattr(parent_module, child_name, module)
return module
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Fix `importlib` examples to insert any newly created modules via
importlib.util.module_from_spec() immediately into sys.modules instead of
after calling loader.exec_module().

Thanks to Benjamin Mintz for finding the bug.