Skip to content

Commit 4e586a4

Browse files
committed
Add helper functions deprecated by importlib-resources
1 parent e6698b5 commit 4e586a4

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

domdf_python_tools/compat/importlib_resources.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,51 @@
22

33
# stdlib
44
import sys
5+
from typing import TextIO
56

67
if sys.version_info[:2] < (3, 7): # pragma: no cover (py37+)
78
# 3rd party
89
import importlib_resources
10+
from importlib_resources._common import normalize_path
11+
912
globals().update(importlib_resources.__dict__)
13+
14+
def read_binary(package: importlib_resources.Package, resource: importlib_resources.Resource) -> bytes:
15+
"""
16+
Return the binary contents of the resource.
17+
"""
18+
19+
return (importlib_resources.files(package) / normalize_path(resource)).read_bytes()
20+
21+
def open_text(
22+
package: importlib_resources.Package,
23+
resource: importlib_resources.Resource,
24+
encoding: str = 'utf-8',
25+
errors: str = 'strict',
26+
) -> TextIO:
27+
"""
28+
Return a file-like object opened for text reading of the resource.
29+
"""
30+
31+
return (importlib_resources.files(package) / normalize_path(resource)).open(
32+
'r',
33+
encoding=encoding,
34+
errors=errors,
35+
)
36+
37+
def read_text(
38+
package: importlib_resources.Package,
39+
resource: importlib_resources.Resource,
40+
encoding: str = 'utf-8',
41+
errors: str = 'strict',
42+
) -> str:
43+
"""
44+
Return the decoded string of the resource.
45+
"""
46+
47+
with importlib_resources.open_text(package, resource, encoding, errors) as fp:
48+
return fp.read()
49+
1050
else: # pragma: no cover (<py39)
1151
# stdlib
1252
import importlib.resources

0 commit comments

Comments
 (0)