Skip to content

Commit

Permalink
Merge pull request #322 from python/feature/typed-open
Browse files Browse the repository at this point in the history
Add type annotations for Traversable.open.
  • Loading branch information
jaraco authored Jan 3, 2025
2 parents 2917dc4 + 8e9503d commit 2addcf2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
18 changes: 15 additions & 3 deletions importlib_resources/abc.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import abc
import io
import itertools
import pathlib
from typing import (
Expand All @@ -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"]
Expand Down Expand Up @@ -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).
Expand All @@ -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:
Expand Down
1 change: 1 addition & 0 deletions newsfragments/317.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add type annotations for Traversable.open.

0 comments on commit 2addcf2

Please sign in to comment.