How to do this in Python? - A "gotcha"
bieffe62 at gmail.com
bieffe62 at gmail.com
Thu Mar 19 10:05:12 EDT 2009
On Mar 18, 6:06 pm, Jim Garrison <j... at acm.org> wrote:
> S Arrowsmith wrote:
> > Jim Garrison <j... at acm.org> wrote:
> >> 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. This would seem to add much more generality... is
> >> it worthy of a PEP?
>
> > class sentinel:
> > def __eq__(self, other):
> > return termination_test()
>
> > for x in iter(callable, sentinel()):
> > ...
>
> > Writing a sensible sentinel.__init__ is left as an exercise....
>
> If I understand correctly, this pattern allows me to create
> an object (instance of class sentinel) that implements whatever
> equality semantics I need to effect loop termination. In the
> case in point, then, I end up with
>
> class sentinel:
> def __eq__(self,other):
> return other=='' or other==b''
>
> with open(filename, "rb") as f:
> for buf in iter(lambda: f.read(1000), sentinel())):
> do_something(buf)
>
> i.e. sentinel is really "object that compares equal to both ''
> and b''". While I appreciate how this works, I think the
> introduction of a whole new class is a bit of overkill for
> what should be expressible in iter()- Hide quoted text -
>
> - Show quoted text -
In the specific case it should not be needed to create a class,
because
at least with python 2.6:
>>> b'' == ''
True
>>> u'' == ''
True
>>>
so you should be able to do:
with open(filename, "rb") as f:
for buf in iter(lambda: f.read(1000), "" ):
do_something(buf)
Ciao
------
FB
More information about the Python-list
mailing list