Skip to content

Commit 1150cd6

Browse files
committed
Add support for loading a package spec on Python 2
1 parent bfaee17 commit 1150cd6

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

importlib_resources/_compat.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,16 @@ class ABC(object): # type: ignore
2121
FileNotFoundError = FileNotFoundError # type: ignore
2222
except NameError:
2323
FileNotFoundError = OSError
24+
25+
26+
class PackageSpec(object):
27+
def __init__(self, **kwargs):
28+
vars(self).update(kwargs)
29+
30+
31+
def package_spec(package):
32+
return getattr(package, '__spec__', None) or \
33+
PackageSpec(
34+
origin=package.__file__,
35+
loader=getattr(package, '__loader__', None),
36+
)

importlib_resources/trees.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import abc
44
import zipp
55

6-
from ._compat import ABC, Path
6+
from ._compat import ABC, Path, package_spec
77

88

99
class Traversable(ABC):
@@ -40,9 +40,10 @@ def is_file(self):
4040

4141
def from_package(package):
4242
"""Return a Traversable object for the given package"""
43-
package_directory = Path(package.__spec__.origin).parent
43+
spec = package_spec(package)
44+
package_directory = Path(spec.origin).parent
4445
try:
45-
archive_path = package.__spec__.loader.archive
46+
archive_path = spec.loader.archive
4647
rel_path = package_directory.relative_to(archive_path)
4748
return zipp.Path(archive_path, str(rel_path) + '/')
4849
except Exception:

0 commit comments

Comments
 (0)