Question

I was looking at the source code to the hasattr built-in function and noticed a couple of lines that piqued my interest:

Py_INCREF(Py_False);
return Py_False;

...

Py_INCREF(Py_True);
return Py_True;

Aren't Py_False and Py_True global values? Just out of sheer curiosity, why is Python keeping a reference count for these variables?

Was it helpful?

Solution

It's to make all object handling uniform. If I'm writing C code that handles a return value from a function, I have to increment and decrement the reference count on that object. If the function returns me True, I don't want to have to check to see if it's one of those special objects to know whether to manipulate its reference count. I can treat all objects identically.

By treating True and False (and None, btw) the same as all other objects, the C code is much simpler throughout.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top