J
Jim Garrison
S said: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()