@@ -1495,20 +1495,34 @@ Note that if ``name`` is a submodule (contains a dot),
1495
1495
Importing a source file directly
1496
1496
''''''''''''''''''''''''''''''''
1497
1497
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.
1499
1504
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
1502
1509
1503
- # For illustrative purposes.
1504
- import tokenize
1505
- file_path = tokenize.__file__
1506
- module_name = tokenize.__name__
1507
1510
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)
1512
1526
1513
1527
1514
1528
Implementing lazy imports
@@ -1534,7 +1548,6 @@ The example below shows how to implement lazy imports::
1534
1548
False
1535
1549
1536
1550
1537
-
1538
1551
Setting up an importer
1539
1552
''''''''''''''''''''''
1540
1553
0 commit comments