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

Jim Garrison jhg at
Wed Mar 18 18:06:50 CET 2009

S Arrowsmith wrote:
> Jim Garrison  <jhg at> 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:, sentinel())):

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()

More information about the Python-list mailing list