Overview
Booleans in Python are implemented as a subclass of integers. There are only two boolean objects:Py_True and Py_False. Both are immortal (never deallocated).
Type Object
PyBool_Type
bool type object.
Type Checking
PyBool_Check
PyObject*
required
Object to check
1 if boolean, 0 otherwise (never fails)
Example:
Boolean Singletons
Py_True
True object. This object is immortal and has no methods.
Example:
Py_False
False object. This object is immortal and has no methods.
Example:
Since Python 3.12,
Py_True and Py_False are immortal. You don’t need to increment their reference counts, but it’s still good practice to do so for compatibility.Testing Truth Values
Py_IsTrue
True singleton. Equivalent to x is True in Python.
PyObject*
required
Object to test
1 if True, 0 otherwise
Example:
Py_IsFalse
False singleton. Equivalent to x is False in Python.
Returns: 1 if False, 0 otherwise
Example:
Creating Booleans
PyBool_FromLong
Py_True or Py_False based on truth value of integer.
long
required
Integer value to convert
Py_True if v is non-zero, Py_False if zero
Example:
Return Macros
Py_RETURN_TRUE
Py_True from a function.
Example:
Py_RETURN_FALSE
Py_False from a function.
Expands to:
Complete Example
Working with Boolean Values
Converting to C bool
Boolean Operations
Comparison with None
Truth Value Testing
For general truth value testing (not just bool objects), use:Best Practices
Use macros for simple returns:
Use PyBool_FromLong for computed results:
Don’t compare by reference unless needed:
See Also
Integer Objects
Booleans are a subclass of int
Object Protocol
Truth value testing
Reference Counting
Immortal objects
