From 8e9503d90943335369219ba3bc088d2bcd4bca7f 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 | 18 +++++++++++++++--- newsfragments/317.feature.rst | 1 + 2 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 newsfragments/317.feature.rst diff --git a/importlib_resources/abc.py b/importlib_resources/abc.py index c0a4cb9..39b0d37 100644 --- a/importlib_resources/abc.py +++ b/importlib_resources/abc.py @@ -1,5 +1,4 @@ import abc -import io import itertools import pathlib from typing import ( @@ -11,9 +10,14 @@ Optional, Protocol, Text, + TextIO, + Union, + overload, runtime_checkable, ) +from typing_extensions import Literal + from .compat.py38 import StrPath __all__ = ["ResourceReader", "Traversable", "TraversableResources"] @@ -138,8 +142,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). @@ -166,7 +178,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.