Python dunder method for `is`

When viewing documents, namely here http://docs.python.org/2/reference/expressions.html#is , I still cannot find the dunder / protocol method that defines the implementation of the Python is keyword. What method does this determine? From what I understand, everything is does this to compare the results of the id function when two objects are called.

+8
python
source share
1 answer

There is no dunder method for is . You cannot override it, and that is intentional. The whole point of is is that it tells you whether two expressions refer to the same value. Therefore, it must be false, by definition, for two different values. Therefore, there is no need to redefine it.

How the documents placed it:

The is and not is operators verify the identifier of an object: x is y is true if and only if x and y are the same object.

(There's a bit more to Docs data models .)


In addition, is does not compare id results.

id just been defined to return "an integer that is guaranteed to be unique and constant for this object throughout its life." This means that is can certainly use id , but I don't know any implementation where it does it.

Saying this, in CPython it does the same under covers - is checks that the pointers are equal, while id translates the pointer into an integer and returns it. Thus, the only difference between its implementation and implementation via id is an additional pair of function calls and a cast that will not compile without machine code ...

But in other implementations, even this may not be true. (Which should be obvious if you think that Jython and PyPy are written in languages ​​that don't even have a pointer.) For example, PyPy is checks that the underlying RPython objects are the same, while id returns the key generated on the fly "(and cached if you later call id with the same value).

+10
source share

All Articles