Skip to content

Commit ba292cc

Browse files
miss-islingtonChrisBarker-NOAAbrettcannonZeroIntensity
authoredOct 10, 2024··
[3.12] gh-121607: Edited source file import recipe to make it more clear (GH-121519) (GH-124081)
gh-121607: Edited source file import recipe to make it more clear (GH-121519) (cherry picked from commit 3880917) Co-authored-by: Chris Barker <[email protected]> Co-authored-by: Brett Cannon <[email protected]> Co-authored-by: Peter Bierma <[email protected]>
1 parent 67f8302 commit ba292cc

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed
 

‎Doc/library/importlib.rst

+25-12
Original file line numberDiff line numberDiff line change
@@ -1495,20 +1495,34 @@ Note that if ``name`` is a submodule (contains a dot),
14951495
Importing a source file directly
14961496
''''''''''''''''''''''''''''''''
14971497

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

1500-
import importlib.util
1501-
import sys
1505+
To import a Python source file directly from a path, use the following recipe::
1506+
1507+
import importlib.util
1508+
import sys
15021509

1503-
# For illustrative purposes.
1504-
import tokenize
1505-
file_path = tokenize.__file__
1506-
module_name = tokenize.__name__
15071510

1508-
spec = importlib.util.spec_from_file_location(module_name, file_path)
1509-
module = importlib.util.module_from_spec(spec)
1510-
sys.modules[module_name] = module
1511-
spec.loader.exec_module(module)
1511+
def import_from_path(module_name, file_path):
1512+
spec = importlib.util.spec_from_file_location(module_name, file_path)
1513+
module = importlib.util.module_from_spec(spec)
1514+
sys.modules[module_name] = module
1515+
spec.loader.exec_module(module)
1516+
return module
1517+
1518+
1519+
# For illustrative purposes only (use of `json` is arbitrary).
1520+
import json
1521+
file_path = json.__file__
1522+
module_name = json.__name__
1523+
1524+
# Similar outcome as `import json`.
1525+
json = import_from_path(module_name, file_path)
15121526

15131527

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

15361550

1537-
15381551
Setting up an importer
15391552
''''''''''''''''''''''
15401553

0 commit comments

Comments
 (0)
Please sign in to comment.