Synook

Python iter()

A seemingly little-known use for the Python iter() built-in: it can be used to tidy up code that would otherwise need a separate statement for assignment.

with open('text') as f:  
    for b in iter(lambda: f.read(1), ''):
        something(b)

instead of:

with open('text') as f:  
    while True:
        b = f.read(1)
        if b == '': break
        something(b)

A small extension to this idea can be constructed to allow for arbitrary exit conditions, as opposed to just equality to a single value:

def until(f, sentinel):  
    while True:
        v = f()
        if sentinel(v): break
        yield v

with open('text') as f:  
    for b in until(lambda: f.read(1), lambda c: c in ('', '\n')):
        something(b)