mirror of
https://github.com/python/cpython.git
synced 2025-09-26 18:29:57 +00:00
gh-121607: Edited source file import recipe to make it more clear (#121519)
Co-authored-by: Brett Cannon <brett@python.org> Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
This commit is contained in:
parent
cd06f5e323
commit
38809171b8
1 changed files with 25 additions and 12 deletions
|
@ -1584,20 +1584,34 @@ Note that if ``name`` is a submodule (contains a dot),
|
||||||
Importing a source file directly
|
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
|
To import a Python source file directly from a path, use the following recipe::
|
||||||
import sys
|
|
||||||
|
|
||||||
# For illustrative purposes.
|
import importlib.util
|
||||||
import tokenize
|
import sys
|
||||||
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)
|
def import_from_path(module_name, file_path):
|
||||||
sys.modules[module_name] = module
|
spec = importlib.util.spec_from_file_location(module_name, file_path)
|
||||||
spec.loader.exec_module(module)
|
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
|
Implementing lazy imports
|
||||||
|
@ -1623,7 +1637,6 @@ The example below shows how to implement lazy imports::
|
||||||
False
|
False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Setting up an importer
|
Setting up an importer
|
||||||
''''''''''''''''''''''
|
''''''''''''''''''''''
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue