Skip to content

Instantly share code, notes, and snippets.

@willmcgugan
Created August 3, 2025 09:00
Show Gist options
  • Save willmcgugan/fcd15c19d3fe13dd85e249fbc5f5eec1 to your computer and use it in GitHub Desktop.
Save willmcgugan/fcd15c19d3fe13dd85e249fbc5f5eec1 to your computer and use it in GitHub Desktop.
from typing import Generator
class SequenceValidator:
def __init__(self) -> None:
self._generator = self.check()
self._consumed = -1
next(self._generator)
def feed(self, text: str) -> tuple[int, bool | None]:
try:
for character in text:
self._consumed += 1
self._generator.send(character)
except StopIteration as stop_iteration:
return (self._consumed, stop_iteration.value)
else:
return (self._consumed, None)
def check(self) -> Generator[None, str, bool | None]:
return False
yield
class BracesNumber(SequenceValidator):
"""A [ followed by 0 or more digits followed by ]"""
def check(self) -> Generator[None, str, bool | None]:
if (yield) != "[":
return False
while (character := (yield)) in "0123456789":
pass
return character == "]"
data = "[123]"
validator = BracesNumber()
for character in data:
print(validator.feed(character))
print("---")
data = "[123)"
validator = BracesNumber()
for character in data:
print(validator.feed(character))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment