from collections import deque class FileContext(object): def __init__(self, file_): self._file = file_ self._line = 0 self._column = 0 self._column_stack = deque() def getc(self): c = self._file.read(1) if(c == "\n"): self._line += 1 self._column_stack.append(self._column) self._column = 0 else: self._column += 1 return c def ungetc(self, c): self._file.seek(self._file.tell() - 1, 0) if(c == "\n"): self._line -= 1 self._column = self._column_stack.pop() else: self._column -= 1