Question about Py_Is and ==

This is really interesting. Unluckily, my knowledge of CPython is really limited. Can someone explain me this or point me to some CPython code or docs?

I forked this question from " Should Py_Is be preferred to ==?" because is OT there.

1 Like

In Python when you write a is b, what it does in C is it checks whether pointers of objects point to the same memory location.

Thus, in CPython, equivalent can be written p_a == p_b. Also, a macro exists, which is called Py_Is. And all it does is exactly that:

#define Py_Is(p_a, p_b) ((p_a) == (p_b))

The rest is context specific, which is potential requirements implementing something similar to Backquotes for deferred expression and issues with full integration of such.

2 Likes

What is your question?

I don’t understand the quoted text. For example:

Why it will break CPython code?

Because if Py_Is and == is no longer the same, any C code that uses == for PyObject pointers, directly or indirectly, will became incorrect. There are about 33 thousands of occurrences of == and != (not counting indirect use, like in memcmp()) in the CPython’s C code. Most of them can be between PyObject pointers. It is not realistic to review every change of == to Py_Is (even if you use some automation and filter out obviously incorrect changes) and do not make any error. Then you need to find all implicit uses, this may be even more difficult, because you do not know how much is left not discovered.

2 Likes