PyCharm shows me that imp is deprecated so I wonder if there any analogue of imp.new_module for importlib.
Asked
Active
Viewed 5,179 times
2 Answers
23
Quoting from documentation (Emphasis mine) -
imp.new_module(name)
Return a new empty module object called name. This object is not inserted in sys.modules.
Deprecated since version 3.4: Use types.ModuleType instead.
Example -
>>> import types
>>> types.ModuleType('name')
<module 'name'>
To show how they are synonymous -
>>> import imp
>>> imp.new_module('name')
<module 'name'>

Community
- 1
- 1

Anand S Kumar
- 88,551
- 18
- 188
- 176
-
5The only problem is, 3.6 documentation does recommend importlib's module_from_spec, but it seems impossible to use it in such a way. Modules constructed with types.ModuleType have None as `__spec__`, but `module_from_spec(None)` doesn't work. – Veky Jun 01 '16 at 13:24
0
Python documentation suggests to us:
Note Use importlib.util.module_from_spec() to create a new module if you wish to set the various import-controlled attributes.
importlib.util.module_from_spec(spec)
is preferred over using types.ModuleType
to create a new module as spec is used to set as many import-controlled attributes on the module as possible.
To import a Python source file directly, we can use the following snippet:
import importlib.util
import sys
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
The example below, we can use to implement lazy imports:
import importlib.util
import sys
def lazy_import(name):
spec = importlib.util.find_spec(name)
loader = importlib.util.LazyLoader(spec.loader)
spec.loader = loader
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
loader.exec_module(module)
return module
>>> lazy_typing = lazy_import("typing")
>>> #lazy_typing is a real module object,
>>> #but it is not loaded in memory yet.
>>> lazy_typing.TYPE_CHECKING
False

NKSM
- 5,422
- 4
- 25
- 38