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

Scott David Daniels Scott.Daniels at Acm.Org
Thu Mar 19 16:01:16 CET 2009


bieffe62 at gmail.com wrote:
> 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

Ah, you misunderstand the short-term expedient that 2.6 took.
Effectively, it simply said, bytes = str.

In 2.6:
     >>> str is bytes
     True
in 3.X:
     >>> str is bytes
     False
     >>> b'' == ''
     False
     >>> type(b''), type('')
     (<class 'bytes'>, <class 'str'>)

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list