Skip to content

Commit

Permalink
In distutils_hack, only add the metadata finder once. In ensure_local…
Browse files Browse the repository at this point in the history
…_distutils, rely on a context manager for reliable manipulation. Fixes #2958.
  • Loading branch information
jaraco committed Dec 23, 2021
1 parent 28f1d47 commit 55e2134
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
19 changes: 16 additions & 3 deletions _distutils_hack/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import re
import importlib
import warnings
import contextlib


is_pypy = '__pypy__' in sys.builtin_module_names
Expand Down Expand Up @@ -52,9 +53,8 @@ def ensure_local_distutils():
# With the DistutilsMetaFinder in place,
# perform an import to cause distutils to be
# loaded from setuptools._distutils. Ref #2906.
add_shim()
importlib.import_module('distutils')
remove_shim()
with shim():
importlib.import_module('distutils')

# check that submodules load as expected
core = importlib.import_module('distutils.core')
Expand Down Expand Up @@ -129,6 +129,19 @@ def frame_file_is_setup(frame):
DISTUTILS_FINDER = DistutilsMetaFinder()


def ensure_shim():
DISTUTILS_FINDER in sys.meta_path or add_shim()


@contextlib.contextmanager
def shim():
add_shim()
try:
yield
finally:
remove_shim()


def add_shim():
sys.meta_path.insert(0, DISTUTILS_FINDER)

Expand Down
1 change: 1 addition & 0 deletions changelog.d/2958.change.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
In distutils_hack, only add the metadata finder once. In ensure_local_distutils, rely on a context manager for reliable manipulation.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class install_with_pth(install):
import os
var = 'SETUPTOOLS_USE_DISTUTILS'
enabled = os.environ.get(var, 'local') == 'local'
enabled and __import__('_distutils_hack').add_shim()
enabled and __import__('_distutils_hack').ensure_shim()
""").lstrip().replace('\n', '; ')

def initialize_options(self):
Expand Down

0 comments on commit 55e2134

Please sign in to comment.