How to do this in Python? - A "gotcha"
Luis Zarrabeitia
kyrie at uh.cu
Wed Mar 18 14:08:35 EDT 2009
Quoting Jim Garrison <jhg at acm.org>:
> Jim Garrison wrote:
> > Luis Zarrabeitia wrote:
> >> On Tuesday 17 March 2009 06:04:36 pm Jim Garrison wrote:
> >> with open(filename, "rb") as f:
> >> for buf in iter(lambda: f.read(1000),''):
> >> do_something(buf)
> >
> > This is the most pythonic solution yet.
> >
> > Thanks to all the responders who took time to ponder this seemingly
> > trivial question. I learned a lot about the Python mind-set.
>
> I just tried the code as given above and it results in an infinite loop.
>
> Since f.read() returns a byte string when in binary mode, the sentinel
> has to be b''. Is there a value that will compare equal to both '' and b''?
Thank you for the correction.
It works in python2.5 (on my Debian, at least), but I can see why it doesn't in
python3.
> It's a shame the iter(o,sentinel) builtin does the
> comparison itself, instead of being defined as iter(callable,callable)
> where the second argument implements the termination test and returns a
> boolean.
A shame indeed. The "takewhile" workaround is way too obfuscated, and to create
a new class only for this purpose is an overkill (and I'd also classify it as
obfuscated).
> This would seem to add much more generality... is
> it worthy of a PEP?
and, it wouldn't need to replace the current sentinel implementation... one
keyword argument, "predicate", would suffice.
+1.
Cheers,
--
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba
http://www.universidad2010.cu
More information about the Python-list
mailing list