views:

219

answers:

1

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?

+13  A: 

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.

Ned Batchelder
Additionally: T F and None are actually objects. They just don't have any methods. http://docs.python.org/c-api/bool.html
Pod
they technically have methods. Every object has methods.
ironfroggy
len(dir(True)) is 54 -- chock *full* of methods. They're just all special (double-underscores-named) ones.
Alex Martelli
Likely Unladen Swallow will change this. This is exactly the kind of things they are trying to optimize.
voyager
@Alex: I think Pod meant that Py_True and Py_False don't have any methods. For example, the documentation for Py_False says: "The Python False object. This object has no methods. It needs to be treated just like any other object with respect to reference counts."
Jason Baker
*"Special cases aren't special enough to break the rules."*
Mike Graham