Skip to content

Commit 18a7c86

Browse files
authored
gh-104212: Explain how to port imp.load_source() (#105978)
Explain how to port removed imp.load_source() to importlib in What's New in Python 3.12.
1 parent a239272 commit 18a7c86

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

Doc/whatsnew/3.12.rst

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1386,6 +1386,21 @@ Removed
13861386
``imp.source_from_cache()`` :func:`importlib.util.source_from_cache`
13871387
================================= =======================================
13881388

1389+
* Replace ``imp.load_source()`` with::
1390+
1391+
import importlib.util
1392+
import importlib.machinery
1393+
1394+
def load_source(modname, filename):
1395+
loader = importlib.machinery.SourceFileLoader(modname, filename)
1396+
spec = importlib.util.spec_from_file_location(modname, filename, loader=loader)
1397+
module = importlib.util.module_from_spec(spec)
1398+
# The module is always executed and not cached in sys.modules.
1399+
# Uncomment the following line to cache the module.
1400+
# sys.modules[module.__name__] = module
1401+
loader.exec_module(module)
1402+
return module
1403+
13891404
* Removed :mod:`!imp` functions and attributes with no replacements:
13901405

13911406
* undocumented functions:
@@ -1394,7 +1409,6 @@ Removed
13941409
* ``imp.load_compiled()``
13951410
* ``imp.load_dynamic()``
13961411
* ``imp.load_package()``
1397-
* ``imp.load_source()``
13981412

13991413
* ``imp.lock_held()``, ``imp.acquire_lock()``, ``imp.release_lock()``:
14001414
the locking scheme has changed in Python 3.3 to per-module locks.

0 commit comments

Comments
 (0)