Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Give precedence to native traversable readers. #297

Merged
merged 3 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
39 changes: 38 additions & 1 deletion importlib_resources/future/adapters.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,44 @@
import functools
import pathlib
from contextlib import suppress
from types import SimpleNamespace

from .. import readers, _adapters


def _block_standard(reader_getter):
"""
Wrap _adapters.TraversableResourcesLoader.get_resource_reader
and intercept any standard library readers.
"""

@functools.wraps(reader_getter)
def wrapper(*args, **kwargs):
"""
If the reader is from the standard library, return None to allow
allow likely newer implementations in this library to take precedence.
"""
try:
reader = reader_getter(*args, **kwargs)
except NotADirectoryError:
# MultiplexedPath may fail on zip subdirectory
return
# Python 3.10+
if reader.__class__.__module__.startswith('importlib.resources.'):
return
# Python 3.8, 3.9
if isinstance(reader, _adapters.CompatibilityFiles) and (
reader.spec.loader.__class__.__module__.startswith('zipimport')
or reader.spec.loader.__class__.__module__.startswith(
'_frozen_importlib_external'
)
):
return
return reader

return wrapper


class TraversableResourcesLoader(_adapters.TraversableResourcesLoader):
"""
Adapt loaders to provide TraversableResources and other
Expand All @@ -15,7 +49,10 @@ class TraversableResourcesLoader(_adapters.TraversableResourcesLoader):
"""

def get_resource_reader(self, name):
return self._standard_reader() or super().get_resource_reader(name)
return (
_block_standard(super().get_resource_reader)(name)
or self._standard_reader()
)

def _standard_reader(self):
return self._zip_reader() or self._namespace_reader() or self._file_reader()
Expand Down
1 change: 1 addition & 0 deletions newsfragments/295.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Future compatibility adapters now ensure that standard library readers are replaced without overriding non-standard readers.
Loading