Skip to content

Commit

Permalink
Fix load_module deprecation warnings for Python >= 3.10.
Browse files Browse the repository at this point in the history
  • Loading branch information
fschulze committed Dec 11, 2024
1 parent da3cc82 commit 3eb99be
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 4 deletions.
2 changes: 1 addition & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Changes

In next release ...

- ...
- Fix ``load_module`` deprecation warnings for Python >= 3.10.

4.5.4 (2024-04-08)
------------------
Expand Down
10 changes: 9 additions & 1 deletion src/chameleon/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()

Expand Down
10 changes: 9 additions & 1 deletion src/chameleon/tests/test_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import tempfile
import unittest
import zipimport
from importlib.util import module_from_spec
from pathlib import Path


Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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')
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down

0 comments on commit 3eb99be

Please sign in to comment.