@@ -1584,20 +1584,34 @@ Note that if ``name`` is a submodule (contains a dot),
15841584Importing a source file directly
15851585''''''''''''''''''''''''''''''''
15861586
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.
15881593
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
15911598
1592- # For illustrative purposes.
1593- import tokenize
1594- file_path = tokenize.__file__
1595- module_name = tokenize.__name__
15961599
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)
16011615
16021616
16031617Implementing lazy imports
@@ -1623,7 +1637,6 @@ The example below shows how to implement lazy imports::
16231637 False
16241638
16251639
1626-
16271640Setting up an importer
16281641''''''''''''''''''''''
16291642
0 commit comments