On Sun, Jan 17, 2016 at 10:05 PM, Ulli Horlacher
<[email protected]> wrote:
> Chris Angelico <[email protected]> wrote:
>> On Sun, Jan 17, 2016 at 8:51 PM, Ulli Horlacher
>> <[email protected]> wrote:
>> > I have seen at several places "x == None" and "x is None" within
>> > if-statements.
>> > What is the difference?
>> > Which term should I prefer and why?
>>
>> tl;dr: Prefer "x is None" as a check.
>
> And for the negation?
> "if not x is None" or "if x is not None"
>
> I have seen the last one several times, but i do not understand it, because:
>
>>>> x=0
>>>> x is not None
> True
>>>> not None
> True
>>>> x is True
> False
There's no actual difference:
>>> dis.dis(lambda x: x is not None)
1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 0 (None)
6 COMPARE_OP 9 (is not)
9 RETURN_VALUE
>>> dis.dis(lambda x: not x is None)
1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 0 (None)
6 COMPARE_OP 9 (is not)
9 RETURN_VALUE
The compiler can tell that "not x is None" is exactly the same thing
as "x is not None". Personally, I'd rather spell it "is not None",
partly because it reads more like English that way, and partly because
one operator is better than two; but you're welcome to spell it "not x
is None" if that has other benefits (eg consistency).
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list