Skip to content

[3.12] gh-121607: Edited source file import recipe to make it more clear (GH-121519) #124081

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 2 commits into from
Oct 10, 2024
Merged
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
37 changes: 25 additions & 12 deletions Doc/library/importlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1495,20 +1495,34 @@ Note that if ``name`` is a submodule (contains a dot),
Importing a source file directly
''''''''''''''''''''''''''''''''

To import a Python source file directly, use the following recipe::
This recipe should be used with caution: it is an approximation of an import
statement where the file path is specified directly, rather than
:data:`sys.path` being searched. Alternatives should first be considered first,
such as modifying :data:`sys.path` when a proper module is required, or using
:func:`runpy.run_path` when the global namespace resulting from running a Python
file is appropriate.

import importlib.util
import sys
To import a Python source file directly from a path, use the following recipe::

import importlib.util
import sys

# For illustrative purposes.
import tokenize
file_path = tokenize.__file__
module_name = tokenize.__name__

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
def import_from_path(module_name, file_path):
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module


# For illustrative purposes only (use of `json` is arbitrary).
import json
file_path = json.__file__
module_name = json.__name__

# Similar outcome as `import json`.
json = import_from_path(module_name, file_path)


Implementing lazy imports
Expand All @@ -1534,7 +1548,6 @@ The example below shows how to implement lazy imports::
False



Setting up an importer
''''''''''''''''''''''

Expand Down
Loading