1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
# noqa: D100,DALL000
# stdlib
import os
import sys
from typing import Any, BinaryIO, TextIO
if sys.version_info[:2] < (3, 9): # pragma: no cover (py39+)
# 3rd party
import importlib_resources
globals().update(importlib_resources.__dict__)
else: # pragma: no cover (<py39)
# stdlib
import importlib.resources
globals().update(importlib.resources.__dict__)
if not ((3, 9) <= sys.version_info < (3, 11)): # pragma: no cover (py39 OR py310):
def _normalize_path(path: Any) -> str:
"""
Normalize a path by ensuring it is a string.
If the resulting string contains path separators, an exception is raised.
"""
parent, file_name = os.path.split(str(path))
if parent:
raise ValueError(f'{path!r} must be only a file name')
return file_name
def open_binary(package: "Package", resource: "Resource") -> BinaryIO:
"""
Return a file-like object opened for binary reading of the resource.
"""
return (files(package) / _normalize_path(resource)).open("rb")
def read_binary(package: "Package", resource: "Resource") -> bytes:
"""
Return the binary contents of the resource.
"""
return (files(package) / _normalize_path(resource)).read_bytes()
def open_text(
package: "Package",
resource: "Resource",
encoding: str = "utf-8",
errors: str = "strict",
) -> TextIO:
"""
Return a file-like object opened for text reading of the resource.
"""
return (files(package) / _normalize_path(resource)).open(
'r',
encoding=encoding,
errors=errors,
)
def read_text(
package: "Package",
resource: "Resource",
encoding: str = "utf-8",
errors: str = "strict",
) -> str:
"""
Return the decoded string of the resource.
"""
with open_text(package, resource, encoding, errors) as fp:
return fp.read()
|