Replace imp with importlib

This project uses the imp module which has been deprecated since Python 3.4 and set for removal in 3.12:
• Raised PendingDeprecationWarning since 3.4 (2014)
• Raised DeprecationWarning since 3.5 (2015)
• Updated DeprecationWarning to say removal in 3.12 since 3.10 (2021)
• Removal planned for 3.12 (2023)

This change removes the dependency on imp in favour of importlib.

Co-authored-by: @jbkkd
Inspired by: @mgorny

https://github.com/jazzband/django-configurations/issues/358
This commit is contained in:
Michal Szczesny 2023-09-08 12:27:47 +01:00 committed by Omer Korner
parent dce5f37a93
commit 27f67a58a4

View file

@ -1,4 +1,5 @@
import imp import importlib.util
from importlib.machinery import PathFinder
import logging import logging
import os import os
import sys import sys
@ -126,25 +127,30 @@ class ConfigurationImporter:
self.name)) self.name))
self.logger.debug(stylize(message)) self.logger.debug(stylize(message))
def find_module(self, fullname, path=None): def find_spec(self, fullname, path=None, target=None):
if fullname is not None and fullname == self.module: if fullname is not None and fullname == self.module:
module = fullname.rsplit('.', 1)[-1] spec = PathFinder.find_spec(fullname, path)
return ConfigurationLoader(self.name, if spec is not None:
imp.find_module(module, path)) return importlib.machinery.ModuleSpec(spec.name,
ConfigurationLoader(self.name, spec),
origin=spec.origin)
return None return None
class ConfigurationLoader: class ConfigurationLoader:
def __init__(self, name, location): def __init__(self, name, spec):
self.name = name self.name = name
self.location = location self.spec = spec
def load_module(self, fullname): def load_module(self, fullname):
if fullname in sys.modules: if fullname in sys.modules:
mod = sys.modules[fullname] # pragma: no cover mod = sys.modules[fullname] # pragma: no cover
else: else:
mod = imp.load_module(fullname, *self.location) mod = importlib.util.module_from_spec(self.spec)
sys.modules[fullname] = mod
self.spec.loader.exec_module(mod)
cls_path = '{0}.{1}'.format(mod.__name__, self.name) cls_path = '{0}.{1}'.format(mod.__name__, self.name)
try: try: