Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions src/PIL/ContainerIO.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,24 @@
from __future__ import annotations

import io
from typing import IO, AnyStr, Generic, Literal


class ContainerIO:
class ContainerIO(Generic[AnyStr]):
"""
A file object that provides read access to a part of an existing
file (for example a TAR file).
"""

def __init__(self, file, offset, length) -> None:
def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None:
"""
Create file object.

:param file: Existing file.
:param offset: Start of region, in bytes.
:param length: Size of region, in bytes.
"""
self.fh = file
self.fh: IO[AnyStr] = file
self.pos = 0
self.offset = offset
self.length = length
Expand All @@ -41,10 +42,10 @@ def __init__(self, file, offset, length) -> None:
##
# Always false.

def isatty(self):
def isatty(self) -> bool:
return False

def seek(self, offset, mode=io.SEEK_SET):
def seek(self, offset: int, mode: Literal[0, 1, 2] = io.SEEK_SET) -> None:
"""
Move file pointer.

Expand All @@ -63,15 +64,15 @@ def seek(self, offset, mode=io.SEEK_SET):
self.pos = max(0, min(self.pos, self.length))
self.fh.seek(self.offset + self.pos)

def tell(self):
def tell(self) -> int:
"""
Get current file pointer.

:returns: Offset from start of region, in bytes.
"""
return self.pos

def read(self, n=0):
def read(self, n: int = 0) -> AnyStr:
"""
Read data.

Expand All @@ -84,17 +85,17 @@ def read(self, n=0):
else:
n = self.length - self.pos
if not n: # EOF
return b"" if "b" in self.fh.mode else ""
return b"" if "b" in self.fh.mode else "" # type: ignore[return-value]
self.pos = self.pos + n
return self.fh.read(n)

def readline(self):
def readline(self) -> AnyStr:
"""
Read a line of text.

:returns: An 8-bit string.
"""
s = b"" if "b" in self.fh.mode else ""
s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment]
newline_character = b"\n" if "b" in self.fh.mode else "\n"
while True:
c = self.read(1)
Expand All @@ -105,7 +106,7 @@ def readline(self):
break
return s

def readlines(self):
def readlines(self) -> list[AnyStr]:
"""
Read multiple lines of text.

Expand Down
2 changes: 1 addition & 1 deletion src/PIL/TarIO.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from . import ContainerIO


class TarIO(ContainerIO.ContainerIO):
class TarIO(ContainerIO.ContainerIO[bytes]):
"""A file object that provides read access to a given member of a TAR file."""

def __init__(self, tarfile: str, file: str) -> None:
Expand Down