From 3eb99be8b24b1fa8357c295d3ad15e3ed8e5d8ad Mon Sep 17 00:00:00 2001 From: Florian Schulze Date: Wed, 11 Dec 2024 11:35:02 +0100 Subject: [PATCH] Fix load_module deprecation warnings for Python >= 3.10. --- CHANGES.rst | 2 +- src/chameleon/loader.py | 10 +++++++++- src/chameleon/tests/test_loader.py | 10 +++++++++- tox.ini | 2 +- 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 40e05baa..7ea933b6 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -3,7 +3,7 @@ Changes In next release ... -- ... +- Fix ``load_module`` deprecation warnings for Python >= 3.10. 4.5.4 (2024-04-08) ------------------ diff --git a/src/chameleon/loader.py b/src/chameleon/loader.py index 5eef54ac..9bef2748 100644 --- a/src/chameleon/loader.py +++ b/src/chameleon/loader.py @@ -12,6 +12,8 @@ import tempfile import warnings from importlib.machinery import SourceFileLoader +from importlib.util import module_from_spec +from importlib.util import spec_from_loader from threading import RLock from typing import TYPE_CHECKING from typing import Any @@ -222,7 +224,13 @@ def _load(self, base: str, filename: str) -> dict[str, Any]: try: module = sys.modules.get(base) if module is None: - module = SourceFileLoader(base, filename).load_module() + loader = SourceFileLoader(base, filename) + spec = spec_from_loader(base, loader) + if spec is None: + raise ModuleNotFoundError(f"{base} ({filename})") + module = module_from_spec(spec) + loader.exec_module(module) + sys.modules[base] = module finally: release_lock() diff --git a/src/chameleon/tests/test_loader.py b/src/chameleon/tests/test_loader.py index a3bfa4fc..f9276ecd 100644 --- a/src/chameleon/tests/test_loader.py +++ b/src/chameleon/tests/test_loader.py @@ -3,6 +3,7 @@ import tempfile import unittest import zipimport +from importlib.util import module_from_spec from pathlib import Path @@ -110,7 +111,13 @@ def _test_load_package(self, command, pkg_extension): (package_path,) = basedir.glob('dist/*' + pkg_extension) importer = zipimport.zipimporter(str(package_path)) - importer.load_module(pkg_name) + if hasattr(importer, 'find_spec'): + spec = importer.find_spec(pkg_name) + module = module_from_spec(spec) + importer.exec_module(module) + sys.modules[pkg_name] = module + else: + importer.load_module(pkg_name) try: self._test_pkg(pkg_name) @@ -170,6 +177,7 @@ def test_build(self): source = "def function(): return %r" % "\xc3\xa6\xc3\xb8\xc3\xa5" module = loader.build(source, "test.xml") + self.assertIn('test', sys.modules) result1 = module['function']() d = {} code = compile(source, 'test.py', 'exec') diff --git a/tox.ini b/tox.ini index 6c15eb55..a84f3e4f 100644 --- a/tox.ini +++ b/tox.ini @@ -23,7 +23,7 @@ deps = pytest setuptools commands = - pytest --doctest-modules + pytest --doctest-modules -W error:"the load_module":DeprecationWarning -W error:"zipimport.zipimporter.load_module":DeprecationWarning {posargs} extras = test setenv =