Skip to content

Instantly share code, notes, and snippets.

@romilly
Created November 14, 2025 08:17
Show Gist options
  • Select an option

  • Save romilly/7370d3cb309b2bd577ca884b4a77ba5a to your computer and use it in GitHub Desktop.

Select an option

Save romilly/7370d3cb309b2bd577ca884b4a77ba5a to your computer and use it in GitHub Desktop.
A TextIO reader that allows one-line lookahead
"""
PeekyReader - A TextIO wrapper that allows peeking at the next line.
"""
from typing import TextIO
class PeekyReader:
"""A TextIO wrapper that allows clients to peek at the next line before reading it."""
def __init__(self, text_io: TextIO):
"""
Initialize PeekyReader with a TextIO object.
Args:
text_io: A text stream (file-like object) to wrap
"""
self._text_io = text_io
self._current_line = text_io.readline()
def peek(self) -> str:
"""
Peek at the next line without consuming it.
Returns:
The next line, or empty string if at EOF
"""
return self._current_line
def readline(self) -> str:
"""
Read and consume the next line.
Returns:
The next line, or empty string if at EOF
"""
line_to_return = self._current_line
self._current_line = self._text_io.readline()
return line_to_return
def close(self) -> None:
"""Close the underlying text stream."""
self._text_io.close()
def __enter__(self):
"""Enter the context manager."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit the context manager and close the underlying text stream."""
self.close()
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment