[Tutor] saveLine
Peter Otten
__peter__ at web.de
Sun Nov 11 14:43:11 EST 2018
Avi Gross wrote:
> Alan and others have answered the questions posed and what I am asking now
> is to look at the function he proposed to keep track of the last five
> lines.
>
> There is nothing wrong with it but I wonder what alternatives people would
> prefer. His code is made for exactly 5 lines to be buffered and is quite
> efficient. But what if you wanted N lines buffered, perhaps showing a
> smaller number of lines on some warnings or errors and the full N in other
> cases?
The standard library features collections.deque. With that:
buffer = collections.deque(maxlen=N)
save_line = buffer.append
This will start with an empty buffer. To preload the buffer:
buffer = collections.deque(itertools.repeat("", N), maxlen=N)
To print the buffer:
print_buffer = sys.stdout.writelines
or, more general:
def print_buffer(items, end=""):
for item in items:
print(item, end=end)
Also, for smallish N:
def print_buffer(items, end=""):
print(*items, sep=end)
More information about the Tutor
mailing list