Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python keep a reference count on False and True?

Tags:

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?

like image 392
Jason Baker Avatar asked Sep 22 '09 14:09

Jason Baker


1 Answers

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.

like image 160
Ned Batchelder Avatar answered Oct 22 '22 11:10

Ned Batchelder