How to do this in Python? - A "gotcha"

Jim Garrison jhg at acm.org
Wed Mar 18 12:23:17 EDT 2009


Andrii V. Mishkovskyi wrote:
> Just before you start writing a PEP, take a look at `takewhile'
> function in `itertools' module. ;)

OK, after reading the itertools docs I'm not sure how to use it
in this context.  takewhile() requires a sequence, and turning
f.read(bufsize) into an iterable requires iter() (no?) which
wants to do its own termination testing.  The following kludge
would subvert iter()'s termination testing but this is starting
to look Perlishly byzantine.

     with open(filename, "rb") as f:
         for buf in itertools.takewhile( \
                 lambda b:b, \
                 iter(lambda: f.read(1000),None)):
             do_something(buf)

As opposed to

     with open(filename, "rb") as f:
         for buf in iter(lambda: f.read(1000), lambda b:b)):
             do_something(buf)

where iter(callable,callable) is defined to

1) call the first argument
2) pass the returned value to the second argument
3) yield the first result and continue if the return value
    from the second call is True, or terminate if False



More information about the Python-list mailing list