2 from typing import BinaryIO, Iterable, Text
4 from ._compat import runtime_checkable, Protocol
7 class ResourceReader(metaclass=abc.ABCMeta):
8 """Abstract base class for loaders to provide resource reading support."""
11 def open_resource(self, resource: Text) -> BinaryIO:
12 """Return an opened, file-like object for binary reading.
14 The 'resource' argument is expected to represent only a file name.
15 If the resource cannot be found, FileNotFoundError is raised.
17 # This deliberately raises FileNotFoundError instead of
18 # NotImplementedError so that if this method is accidentally called,
19 # it'll still do the right thing.
20 raise FileNotFoundError
23 def resource_path(self, resource: Text) -> Text:
24 """Return the file system path to the specified resource.
26 The 'resource' argument is expected to represent only a file name.
27 If the resource does not exist on the file system, raise
30 # This deliberately raises FileNotFoundError instead of
31 # NotImplementedError so that if this method is accidentally called,
32 # it'll still do the right thing.
33 raise FileNotFoundError
36 def is_resource(self, path: Text) -> bool:
37 """Return True if the named 'path' is a resource.
39 Files are resources, directories are not.
41 raise FileNotFoundError
44 def contents(self) -> Iterable[str]:
45 """Return an iterable of entries in `package`."""
46 raise FileNotFoundError
50 class Traversable(Protocol):
52 An object with a subset of pathlib.Path methods suitable for
53 traversing directories and opening files.
59 Yield Traversable objects in self
64 Read contents of self as bytes
66 with self.open('rb') as strm:
69 def read_text(self, encoding=None):
71 Read contents of self as text
73 with self.open(encoding=encoding) as strm:
77 def is_dir(self) -> bool:
79 Return True if self is a directory
83 def is_file(self) -> bool:
85 Return True if self is a file
89 def joinpath(self, child):
91 Return Traversable child in self
94 def __truediv__(self, child):
96 Return Traversable child in self
98 return self.joinpath(child)
101 def open(self, mode='r', *args, **kwargs):
103 mode may be 'r' or 'rb' to open as text or binary. Return a handle
104 suitable for reading (same as pathlib.Path.open).
106 When opening as text, accepts encoding parameters such as those
107 accepted by io.TextIOWrapper.
110 @abc.abstractproperty
111 def name(self) -> str:
113 The base name of this object without any parent references.
117 class TraversableResources(ResourceReader):
119 The required interface for providing traversable
125 """Return a Traversable object for the loaded package."""
127 def open_resource(self, resource):
128 return self.files().joinpath(resource).open('rb')
130 def resource_path(self, resource):
131 raise FileNotFoundError(resource)
133 def is_resource(self, path):
134 return self.files().joinpath(path).is_file()
137 return (item.name for item in self.files().iterdir())