from collections import deque

def search(lines,pattern,history=5):
    previous_lines = deque(maxlen=history)
    for line in lines:
        if pattern in line:
            yield line,previous_lines

if __name__ == "__main__":
    with open('history') as f:
        for line,prevlines in search(f,'python',5):
            for pline in prevlines:
                print( pline , end ='')
                print('-' * 20)

Can someone help me to understand what the above snippet does ?

The code finds the lines containing the word 'python' in the file named 'history'. The search function yields the line containing that word and a deque of at most five lines immediately before that line.
For example if the file contains

my python

the search function will yield

('my python\n', deque(['baz\n','qux\n','spam\n','eggs\n','ham\n']))

Edited 1 Year Ago by Gribouillis

A good technique to understand code is to break it up in smaller parts.
For this is interactive interpreter great to us,
also us print() in code on places you wonder what's happends.
So lets say you wonder about deque(maxlen=history).

>>> from collections import deque
>>> lst = [1, 2, 3, 4, 5, 6, 7]
>>> d = deque(maxlen=3)
>>> for item in lst:
...     d.append(item)
...     print(d)
deque([1], maxlen=3)
deque([1, 2], maxlen=3)
deque([1, 2, 3], maxlen=3)
deque([2, 3, 4], maxlen=3)
deque([3, 4, 5], maxlen=3)
deque([4, 5, 6], maxlen=3)
deque([5, 6, 7], maxlen=3)

So here it easy to see that it fill up a list,
up to 3 elements max and then it start to throw out the first vaules in.

Edited 1 Year Ago by snippsat

This article has been dead for over six months. Start a new discussion instead.