8000 [3.8] bpo-42531: Teach importlib.resources.path to handle packages without __file__ by wkschwartz · Pull Request #23611 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

[3.8] bpo-42531: Teach importlib.resources.path to handle packages without __file__ #23611

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

Merged
merged 4 commits into from
Jan 16, 2021
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
8 changes: 5 additions & 3 deletions Lib/importlib/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,11 @@ def path(package: Package, resource: Resource) -> Iterator[Path]:
_check_location(package)
# Fall-through for both the lack of resource_path() *and* if
# resource_path() raises FileNotFoundError.
package_directory = Path(package.__spec__.origin).parent
file_path = package_directory / resource
if file_path.exists():
file_path = None
if package.__spec__.origin is not None:
package_directory = Path(package.__spec__.origin).parent
file_path = package_directory / resource
if file_path is not None and file_path.exists():
yield file_path
else:
with open_binary(package, resource) as fp:
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_importlib/test_path.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import io
import unittest

from importlib import resources
Expand Down Expand Up @@ -27,6 +28,17 @@ class PathDiskTests(PathTests, unittest.TestCase):
data = data01


class PathMemoryTests(PathTests, unittest.TestCase):
def setUp(self):
file = io.BytesIO(b'Hello, UTF-8 world!\n')
self.addCleanup(file.close)
self.data = util.create_package(
file=file, path=FileNotFoundError("package exists only in memory")
)
self.data.__spec__.origin = None
self.data.__spec__.has_location = False


class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase):
def test_remove_in_context_manager(self):
# It is not an error if the file that was temporarily stashed on the
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:func:`importlib.resources.path` now works for :term:`package`\ s missing the optional :attr:`__file__` attribute (more specifically, packages whose :attr:`__spec__`\ ``.``\ :attr:`~importlib.machinery.ModuleSpec.origin` :keyword:`is` :data:`None`).
0