Python Glossary Русский

all Python 3until 3.12Removed from the standard libraryterm

imp

removed modules

Module for low-level import work: finding, loading and reloading modules. Removed in Python 3.12; use importlib instead.

Syntax

import imp  # до 3.12

imp exposed the internals of the old import system. Since Python 3.1 it was rewritten in pure Python as importlib, and imp became a wrapper: deprecated in 3.4, removed in 3.12. How to rewrite: imp.reload(m) becomes importlib.reload(m); imp.load_module(...) becomes importlib.import_module(name); imp.find_module(name) becomes importlib.util.find_spec(name); imp.new_module(name) becomes types.ModuleType(name); imp.get_magic() becomes importlib.util.MAGIC_NUMBER. Loading a module from a file (formerly imp.load_source) goes through importlib.util.spec_from_file_location() and module_from_spec(), as in the example.

Examples

# Python 3.12+
try:
    import imp
except ModuleNotFoundError as e:
    print(type(e).__name__)  # → ModuleNotFoundError
# Python 3.12+
import importlib, importlib.util, types
json = importlib.import_module('json')
print(importlib.reload(json).__name__)  # → json
print(importlib.util.find_spec('json') is not None)  # → True
print(types.ModuleType('demo').__name__)  # → demo
# Python 3.12+
import importlib.util
with open('plugin.py', 'w') as f:
    f.write('VALUE = 7\n')
spec = importlib.util.spec_from_file_location('plugin', 'plugin.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
print(module.VALUE)  # → 7
import imp, json
print(imp.reload(json).__name__)  # → json
print(imp.new_module('demo').__name__)  # → demo

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy