Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add importlib.util.allowing_all_extensions().
  • Loading branch information
ericsnowcurrently committed May 8, 2023
commit 47059776bdb14985b3979f5eec53af0360f9b330
37 changes: 37 additions & 0 deletions Lib/importlib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,43 @@ def find_spec(name, package=None):
return spec


# Normally we would use contextlib.contextmanager. However, this module
# is imported by runpy, which means we want to avoid any unnecessary
# dependencies. Thus we use a class.

class allowing_all_extensions:
"""A context manager that lets users skip the compatibility check.

Normally, extensions that do not support multiple interpreters
may not be imported in a subinterpreter. That implies modules
that do not implement multi-phase init.

Likewise for modules import in a subinterpeter with its own GIL
when the extension does not support a per-interpreter GIL. This
implies the module does not have a Py_mod_multiple_interpreters slot
set to Py_MOD_PER_INTERPRETER_GIL_SUPPORTED.

In both cases, this context manager may be used to temporarily
disable the check for compatible extension modules.
"""

def __init__(self, enabled):
self.enabled = enabled

def __enter__(self):
self.old = _imp._override_multi_interp_extensions_check(self.override)
return self

def __exit__(self, *args):
old = self.old
del self.old
_imp._override_multi_interp_extensions_check(old)

@property
def override(self):
return 1 if self.enabled else 0


class _LazyModule(types.ModuleType):

"""A subclass of the module type which triggers loading upon attribute access."""
Expand Down
2 changes: 2 additions & 0 deletions Lib/test/support/import_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ def multi_interp_extensions_check(enabled=True):
It overrides the PyInterpreterConfig.check_multi_interp_extensions
setting (see support.run_in_subinterp_with_config() and
_xxsubinterpreters.create()).

Also see importlib.utils.allowing_all_extensions().
"""
old = _imp._override_multi_interp_extensions_check(1 if enabled else -1)
try:
Expand Down