Skip to content

Commit 8b5dd60

Browse files
committed
Add Python 2.7 compatibility for modules_setup/cleanup
1 parent 571bb95 commit 8b5dd60

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

importlib_resources/tests/_compat.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
try:
2-
# Python 3.10
32
from test.support import import_helper
43
except ImportError:
5-
class import_helper:
6-
from test.support import modules_setup, modules_cleanup
4+
try:
5+
# Python 3.9 and earlier
6+
class import_helper:
7+
from test.support import modules_setup, modules_cleanup
8+
except ImportError:
9+
from . import py27compat
10+
11+
class import_helper:
12+
modules_setup = staticmethod(py27compat.modules_setup)
13+
modules_cleanup = staticmethod(py27compat.modules_cleanup)
714

815

916
try:
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import sys
2+
3+
4+
def modules_setup():
5+
return sys.modules.copy(),
6+
7+
8+
def modules_cleanup(oldmodules):
9+
# Encoders/decoders are registered permanently within the internal
10+
# codec cache. If we destroy the corresponding modules their
11+
# globals will be set to None which will trip up the cached functions.
12+
encodings = [(k, v) for k, v in sys.modules.items()
13+
if k.startswith('encodings.')]
14+
sys.modules.clear()
15+
sys.modules.update(encodings)
16+
# XXX: This kind of problem can affect more than just encodings.
17+
# In particular extension modules (such as _ssl) don't cope
18+
# with reloading properly. Really, test modules should be cleaning
19+
# out the test specific modules they know they added (ala test_runpy)
20+
# rather than relying on this function (as test_importhooks and test_pkg
21+
# do currently). Implicitly imported *real* modules should be left alone
22+
# (see issue 10556).
23+
sys.modules.update(oldmodules)

0 commit comments

Comments
 (0)