S Arrowsmith wrote:
Jim Garrison <j...@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()
--
http://mail.python.org/mailman/listinfo/python-list