@@ -1584,20 +1584,34 @@ Note that if ``name`` is a submodule (contains a dot),
1584
1584
Importing a source file directly
1585
1585
''''''''''''''''''''''''''''''''
1586
1586
1587
- To import a Python source file directly, use the following recipe::
1587
+ This recipe should be used with caution: it is an approximation of an import
1588
+ statement where the file path is specified directly, rather than
1589
+ :data: `sys.path ` being searched. Alternatives should first be considered first,
1590
+ such as modifying :data: `sys.path ` when a proper module is required, or using
1591
+ :func: `runpy.run_path ` when the global namespace resulting from running a Python
1592
+ file is appropriate.
1588
1593
1589
- import importlib.util
1590
- import sys
1594
+ To import a Python source file directly from a path, use the following recipe::
1595
+
1596
+ import importlib.util
1597
+ import sys
1591
1598
1592
- # For illustrative purposes.
1593
- import tokenize
1594
- file_path = tokenize.__file__
1595
- module_name = tokenize.__name__
1596
1599
1597
- spec = importlib.util.spec_from_file_location(module_name, file_path)
1598
- module = importlib.util.module_from_spec(spec)
1599
- sys.modules[module_name] = module
1600
- spec.loader.exec_module(module)
1600
+ def import_from_path(module_name, file_path):
1601
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
1602
+ module = importlib.util.module_from_spec(spec)
1603
+ sys.modules[module_name] = module
1604
+ spec.loader.exec_module(module)
1605
+ return module
1606
+
1607
+
1608
+ # For illustrative purposes only (use of `json` is arbitrary).
1609
+ import json
1610
+ file_path = json.__file__
1611
+ module_name = json.__name__
1612
+
1613
+ # Similar outcome as `import json`.
1614
+ json = import_from_path(module_name, file_path)
1601
1615
1602
1616
1603
1617
Implementing lazy imports
@@ -1623,7 +1637,6 @@ The example below shows how to implement lazy imports::
1623
1637
False
1624
1638
1625
1639
1626
-
1627
1640
Setting up an importer
1628
1641
''''''''''''''''''''''
1629
1642
0 commit comments