bpo-26131: Deprecate usage of load_module() (GH-23469)

Raise an ImportWarning when the import system falls back on load_module(). As for implementations of load_module(), raise a DeprecationWarning.
This commit is contained in:
Brett Cannon 2020-12-04 15:39:21 -08:00 committed by GitHub
parent 79c1849b9e
commit 2de5097ba4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 3245 additions and 3034 deletions

View file

@ -20,6 +20,12 @@ work. One should use importlib as the public-facing version of this module.
# reference any injected objects! This includes not only global code but also
# anything specified at the class level.
def _object_name(obj):
try:
return obj.__qualname__
except AttributeError:
return type(obj).__qualname__
# Bootstrap-related code ######################################################
# Modules injected manually by _setup()
@ -272,6 +278,9 @@ def _load_module_shim(self, fullname):
This method is deprecated. Use loader.exec_module instead.
"""
msg = ("the load_module() method is deprecated and slated for removal in "
"Python 3.12; use exec_module() instead")
_warnings.warn(msg, DeprecationWarning)
spec = spec_from_loader(fullname, self)
if fullname in sys.modules:
module = sys.modules[fullname]
@ -612,9 +621,9 @@ def _exec(spec, module):
else:
_init_module_attrs(spec, module, override=True)
if not hasattr(spec.loader, 'exec_module'):
# (issue19713) Once BuiltinImporter and ExtensionFileLoader
# have exec_module() implemented, we can add a deprecation
# warning here.
msg = (f"{_object_name(spec.loader)}.exec_module() not found; "
"falling back to load_module()")
_warnings.warn(msg, ImportWarning)
spec.loader.load_module(name)
else:
spec.loader.exec_module(module)
@ -627,9 +636,8 @@ def _exec(spec, module):
def _load_backward_compatible(spec):
# (issue19713) Once BuiltinImporter and ExtensionFileLoader
# have exec_module() implemented, we can add a deprecation
# warning here.
# It is assumed that all callers have been warned about using load_module()
# appropriately before calling this function.
try:
spec.loader.load_module(spec.name)
except:
@ -668,6 +676,9 @@ def _load_unlocked(spec):
if spec.loader is not None:
# Not a namespace package.
if not hasattr(spec.loader, 'exec_module'):
msg = (f"{_object_name(spec.loader)}.exec_module() not found; "
"falling back to load_module()")
_warnings.warn(msg, ImportWarning)
return _load_backward_compatible(spec)
module = module_from_spec(spec)
@ -851,6 +862,7 @@ class FrozenImporter:
This method is deprecated. Use exec_module() instead.
"""
# Warning about deprecation implemented in _load_module_shim().
return _load_module_shim(cls, fullname)
@classmethod