Skip to content

Commit

Permalink
Add contextmanager support to IO class (#68)
Browse files Browse the repository at this point in the history
  • Loading branch information
twizmwazin authored Jan 20, 2024
1 parent 80a9fc2 commit e075567
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions python/binharness/types/io.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""binharness.types.io - Type definition for file-like objects."""
from __future__ import annotations

from typing import AnyStr, Protocol
from typing import TYPE_CHECKING, AnyStr, ContextManager, Protocol

if TYPE_CHECKING:
from types import TracebackType

class IO(Protocol[AnyStr]):

class IO(ContextManager["IO[AnyStr]"], Protocol[AnyStr]):
"""A file-like object."""

def close(self: IO[AnyStr]) -> None:
Expand Down Expand Up @@ -46,3 +49,17 @@ def write(self: IO[AnyStr], s: AnyStr) -> int | None:

def writelines(self: IO[AnyStr], lines: list[AnyStr]) -> None:
"""Write lines to the file."""

def __enter__(self: IO[AnyStr]) -> IO[AnyStr]:
"""Enter the runtime context related to this object."""
return self

def __exit__(
self: IO[AnyStr],
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""Exit the runtime context and close the file if it's open."""
if not self.closed:
self.close()

0 comments on commit e075567

Please sign in to comment.