Style question (Poll)
Terry Reedy
tjreedy at udel.edu
Wed Mar 14 17:16:05 EDT 2012
On 3/14/2012 4:49 PM, Arnaud Delobelle wrote:
> On 14 March 2012 20:37, Croepha<croepha at gmail.com> wrote:
>> Which is preferred:
>>
>> for value in list:
>> if not value is another_value:
>> value.do_something()
>> break
Do you really mean 'is' or '=='?
If you mean x is not y, write it that way.
'not x is y' can be misread and misunderstood, depending on whether
the 'is' is true or not.
>>> not 1 is 1
False
>>> not (1 is 1)
False
>>> (not 1) is 1
False
Does not matter how read.
>>> not (1 is 0)
True
>>> (not 1) is 0
False
>>> not 1 is 0
True
Does matter how read.
>> if list and not list[0] is another_value:
>> list[0].do_something()
Or
try:
value = mylist[0]
if value is not another_value: value.dosomething
except IndexError:
pass
I would not do this in this case of index 0, but if the index were a
complicated expression or expensive function call, making 'if list' an
inadequate test, I might.
> Hard to say, since they don't do the same thing :)
>
> I suspect you meant:
>
> for value in list:
> if not value is another_value:
> value.do_something()
> break
>
> I always feel uncomfortable with this because it's misleading: a loop
> that never loops.
I agree. Please do not do this in public ;-).
--
Terry Jan Reedy
More information about the Python-list
mailing list