Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `None is None is None` return True? [duplicate]

Today, in an interview, the CTO asked me what looks like an easy question,

What does this statement return ? :

None is None is None 

I thought Python executed the first operation None is None and would return True. After that, it would compare True is None which would return False. But, to my surprise, the right answer is True. I am trying to find answer to this question, but after a couple of days searching I didn't find anything. Can someone explain why this happens?

like image 644
Vladyslav Avatar asked Jun 20 '18 14:06

Vladyslav


People also ask

Why is None and not == None?

None is a singleton object (there only ever exists one None ). is checks to see if the object is the same object, while == just checks if they are equivalent. But since there is only one None , they will always be the same, and is will return True.

How do I fix None in Python?

Fix input() returning None in Python # The input() function most commonly returns None when passing it a call to the print() function. To get around this, make sure to pass a string to the input() function and not a call to the print() function. Copied!

Is None equal to false?

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string.

Does None return true in Python?

It's one of Python's Magic Methods. The confusing thing is, that bool(None) returns False , so if x is None, if x works as you expect it to. However, there are other values that are evaluated as False . The most prominent example is an empty list.


1 Answers

The bytecode shows that two comparisons are being performed here with the middle being duplicated:

>>> import dis >>> def a(): ...     return None is None is None ...  >>> dis.dis(a)   2           0 LOAD_CONST               0 (None)               3 LOAD_CONST               0 (None)               6 DUP_TOP               7 ROT_THREE               8 COMPARE_OP               8 (is)              11 JUMP_IF_FALSE_OR_POP    21              14 LOAD_CONST               0 (None)              17 COMPARE_OP               8 (is)              20 RETURN_VALUE         >>   21 ROT_TWO              22 POP_TOP              23 RETURN_VALUE 

As stated in the docs for comparisons this is because these operators chain together.

a op b op c will be translated to a op b and b op c (note b is duplicated in the bytecode as shown above)

like image 188
shuttle87 Avatar answered Oct 13 '22 07:10

shuttle87