What does the eat operator do in Python?

I was (maybe wrongfully) thinking that the is operator is doing an id () comparison.

 >>> x = 10 >>> y = 10 >>> id(x) 1815480092 >>> id(y) 1815480092 >>> x is y True 

However, with val is not None , it seems like it's not that simple.

 >>> id(not None) 2001680 >>> id(None) 2053536 >>> val = 10 >>> id(val) 1815480092 >>> val is not None True 

Then what does the 'is' operator do? Is this just a mapping of object identifiers, only I assumed? If so, is val is not None interpreted in Python as not (val is None) ?

+6
source share
3 answers

You missed that is not also an operator.

Without is , the regular not operator returns a boolean:

 >>> not None True 

not None is thus the inverse Boolean value of ' None . In a boolean context, None is false:

 >>> bool(None) False 

therefore, not None is set to boolean True .

Both None and True are also objects, and both have a memory address (the id() value returns for CPython Python implementation):

 >>> id(True) 4440103488 >>> id(not None) 4440103488 >>> id(None) 4440184448 

is checks to see if two references point to the same object; if something is the same object, it will have the same id() . is returns a boolean value, True or False .

is not is the inverse of the is operator. This is the equivalent of not (op1 is op2) , in a single statement. It should not be read as op1 is (not op2) here:

 >>> 1 is not None # is 1 a different object from None? True >>> 1 is (not None) # is 1 the same object as True? False 
+10
source

As a complement to Martijn Pieters answer, None , True and False are single point. There is only one instance of each of these values, so it is safe to use is to test them.

 >>> id(True) 8851952 >>> id(False) 8851920 >>> id(None) 8559264 >>> id(not None) 8851952 >>> id(1 == 0) 8851920 >>> id(1 == 1) 8851952 
+3
source

Python tries to imitate the syntax of the English language to make it more understandable to humans, but in this case, the operator's priority is a bit confusing.

 >>> val is not None True 

In English, we ask if val value represented by the same object as None . In the above example, val=10 , so the answer is (correct) True .

However, from a logical, syntactical point of view, you broke the phrase and suggested that this:

 >>> val is (not None) False 

which, when enclosed in the corresponding pathoids, returns the expected result ( False ).

As @Martijn Pieters notes, is not its own operator , and it is the only operator working here.

If you want to write it as an ambiguous statement, using only those that do not contain spaces, you can write:

 >>> not (val is None) True 

But you cannot say the β€œintended” expression in English, or perhaps even write it in pseudo-code.

0
source

Source: https://habr.com/ru/post/951891/


All Articles