From 916c4afaad8b5ce4de8797c6fc7e4dde68e4a046 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Fri, 3 Jan 2025 09:54:39 -0500 Subject: [PATCH] Add type annotations for Traversable.open. Closes #317. --- importlib_resources/abc.py | 19 ++++++++++++++----- newsfragments/317.feature.rst | 1 + 2 files changed, 15 insertions(+), 5 deletions(-) create mode 100644 newsfragments/317.feature.rst diff --git a/importlib_resources/abc.py b/importlib_resources/abc.py index 7a58dd2..1832541 100644 --- a/importlib_resources/abc.py +++ b/importlib_resources/abc.py @@ -1,9 +1,10 @@ import abc -import io import itertools import pathlib -from typing import Any, BinaryIO, Iterable, Iterator, NoReturn, Text, Optional -from typing import runtime_checkable, Protocol +from typing import Any, BinaryIO, Iterable, Iterator, NoReturn, Text, TextIO, Optional +from typing import overload, runtime_checkable +from typing import Protocol, Union +from typing_extensions import Literal from .compat.py38 import StrPath @@ -130,8 +131,16 @@ def __truediv__(self, child: StrPath) -> "Traversable": """ return self.joinpath(child) + @overload + def open(self, mode: Literal['r'] = 'r', *args: Any, **kwargs: Any) -> TextIO: ... + + @overload + def open(self, mode: Literal['rb'], *args: Any, **kwargs: Any) -> BinaryIO: ... + @abc.abstractmethod - def open(self, mode='r', *args, **kwargs): + def open( + self, mode: str = 'r', *args: Any, **kwargs: Any + ) -> Union[TextIO, BinaryIO]: """ mode may be 'r' or 'rb' to open as text or binary. Return a handle suitable for reading (same as pathlib.Path.open). @@ -158,7 +167,7 @@ class TraversableResources(ResourceReader): def files(self) -> "Traversable": """Return a Traversable object for the loaded package.""" - def open_resource(self, resource: StrPath) -> io.BufferedReader: + def open_resource(self, resource: StrPath) -> BinaryIO: return self.files().joinpath(resource).open('rb') def resource_path(self, resource: Any) -> NoReturn: diff --git a/newsfragments/317.feature.rst b/newsfragments/317.feature.rst new file mode 100644 index 0000000..25b1a97 --- /dev/null +++ b/newsfragments/317.feature.rst @@ -0,0 +1 @@ +Add type annotations for Traversable.open.