7 from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any
11 Package = Union[types.ModuleType, str]
16 @functools.wraps(func)
17 def wrapper(*args, **kwargs):
19 f"{func.__name__} is deprecated. Use files() instead. "
20 "Refer to https://importlib-resources.readthedocs.io"
21 "/en/latest/using.html#migrating-from-legacy for migration advice.",
25 return func(*args, **kwargs)
30 def normalize_path(path):
32 """Normalize a path by ensuring it is a string.
34 If the resulting string contains path separators, an exception is raised.
37 parent, file_name = os.path.split(str_path)
39 raise ValueError(f'{path!r} must be only a file name')
44 def open_binary(package: Package, resource: Resource) -> BinaryIO:
45 """Return a file-like object opened for binary reading of the resource."""
46 return (_common.files(package) / normalize_path(resource)).open('rb')
50 def read_binary(package: Package, resource: Resource) -> bytes:
51 """Return the binary contents of the resource."""
52 return (_common.files(package) / normalize_path(resource)).read_bytes()
59 encoding: str = 'utf-8',
60 errors: str = 'strict',
62 """Return a file-like object opened for text reading of the resource."""
63 return (_common.files(package) / normalize_path(resource)).open(
64 'r', encoding=encoding, errors=errors
72 encoding: str = 'utf-8',
73 errors: str = 'strict',
75 """Return the decoded string of the resource.
77 The decoding-related arguments have the same semantics as those of
80 with open_text(package, resource, encoding, errors) as fp:
85 def contents(package: Package) -> Iterable[str]:
86 """Return an iterable of entries in `package`.
88 Note that not all entries are resources. Specifically, directories are
89 not considered resources. Use `is_resource()` on each entry returned here
90 to check if it is a resource or not.
92 return [path.name for path in _common.files(package).iterdir()]
96 def is_resource(package: Package, name: str) -> bool:
97 """True if `name` is a resource inside `package`.
99 Directories are *not* resources.
101 resource = normalize_path(name)
103 traversable.name == resource and traversable.is_file()
104 for traversable in _common.files(package).iterdir()
112 ) -> ContextManager[pathlib.Path]:
113 """A context manager providing a file path object to the resource.
115 If the resource does not already exist on its own on the file system,
116 a temporary file will be created. If the file was created, the file
117 will be deleted upon exiting the context manager (no exception is
118 raised if the file was deleted prior to the context manager
121 return _common.as_file(_common.files(package) / normalize_path(resource))