简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM