Skip to content

_common: make as_file return the real file on os.PathLike #232

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

Closed
wants to merge 1 commit into from
Closed
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
11 changes: 10 additions & 1 deletion importlib_resources/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,17 @@ def as_file(path):

@as_file.register(pathlib.Path)
@contextlib.contextmanager
def _(path):
def _as_file_pathlib(path):
"""
Degenerate behavior for pathlib.Path objects.
"""
yield path


@as_file.register(os.PathLike)
@contextlib.contextmanager
def _as_file_pathlike(path):
"""
Degenerate behavior for os.PathLike objects.
"""
yield pathlib.Path(os.fspath(path))
37 changes: 37 additions & 0 deletions importlib_resources/tests/test_path.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import io
import os
import pathlib
import unittest

import importlib_resources as resources
from importlib_resources.abc import TraversableResources
from . import data01
from . import util

Expand Down Expand Up @@ -57,5 +60,39 @@ def test_remove_in_context_manager(self):
path.unlink()


class PathLikeTests(PathTests, unittest.TestCase):
class PathLikeTraversable:
"""pathlib.Path proxy, is os.PathLike but is not pathlib.Path"""

def __init__(self, *args, **kwargs):
self._path = pathlib.Path(*args, **kwargs)

def __fspath__(self):
return os.fspath(self._path)

def joinpath(self, other):
return self.__class__(self, other)

__truediv__ = joinpath

@property
def parent(self):
return self.__class__(self._path.parent)

class PathLikeResources(TraversableResources):
def __init__(self, loader):
self.path = PathLikeTests.PathLikeTraversable(loader.path).parent

def get_resource_reader(self, package):
return self

def files(self):
return self.path

def setUp(self):
reader = self.PathLikeResources(data01.__loader__)
self.data = util.create_package_from_loader(reader)


if __name__ == '__main__':
unittest.main()