Skip to content

Commit 501190d

Browse files
committed
Employ Multiplexer in _compat.LoaderAdapter.get_resource_reader
1 parent 2ff3dc3 commit 501190d

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

importlib_resources/_compat.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,16 @@ def _native_reader(spec):
106106
reader = _available_reader(spec)
107107
return reader if hasattr(reader, 'files') else None
108108

109+
def _namespace_reader(spec):
110+
from . import namespace
111+
if 'NamespaceLoader' not in spec.loader.__class__.__name__:
112+
return
113+
return namespace.Multiplexed.load(spec.submodule_search_locations)
114+
109115
return (
110116
# native reader if it supplies 'files'
111117
_native_reader(self.spec) or
118+
_namespace_reader(self.spec) or
112119
# local ZipReader if a zip module
113120
_zip_reader(self.spec) or
114121
# local FileReader

importlib_resources/namespace.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,34 @@
1+
import os
12
import itertools
2-
from ._compat import suppress
3+
from ._compat import suppress, ZipPath, Path
34
from .abc import Traversable
45

56

7+
def infer_path(path):
8+
return resolve_zip_path(path) or Path(path)
9+
10+
11+
def resolve_zip_path(candidate, tail=''):
12+
if not candidate:
13+
return
14+
try:
15+
return ZipPath(candidate, at=tail)
16+
except Exception:
17+
new_tail = os.path.basename(candidate) + '/' + tail
18+
new_base = os.path.dirname(candidate)
19+
return resolve_zip_path(new_base, new_tail)
20+
21+
622
class Multiplexed(Traversable):
723
"""
824
Given a series of Traversable objects, implement a merged
925
version of the interface across all objects. Useful for
1026
namespace packages which may be multihomed at a single
1127
name.
1228
"""
29+
@classmethod
30+
def load(cls, paths):
31+
return cls(map(cls._infer_path, paths))
1332

1433
def __init__(self, *paths):
1534
self._paths = paths

0 commit comments

Comments
 (0)