Skip to content

Commit

Permalink
Merge pull request #297 from python/feature/better-native-reader-support
Browse files Browse the repository at this point in the history
Give precedence to native traversable readers.
  • Loading branch information
jaraco authored Mar 12, 2024
2 parents 56bd2b9 + 6d48bc9 commit ec50a15
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
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.

0 comments on commit ec50a15

Please sign in to comment.