Skip to main content

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

The Python bool type object.

Type Checking

PyBool_Check

Check if object is a boolean (True or False).
PyObject*
required
Object to check
Returns: 1 if boolean, 0 otherwise (never fails) Example:

Boolean Singletons

Py_True

The Python True object. This object is immortal and has no methods. Example:

Py_False

The Python 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

Test if object is the True singleton. Equivalent to x is True in Python.
PyObject*
required
Object to test
Returns: 1 if True, 0 otherwise Example:

Py_IsFalse

Test if object is the False singleton. Equivalent to x is False in Python. Returns: 1 if False, 0 otherwise Example:

Creating Booleans

PyBool_FromLong

Return Py_True or Py_False based on truth value of integer.
long
required
Integer value to convert
Returns: Py_True if v is non-zero, Py_False if zero Example:
Common usage:

Return Macros

Py_RETURN_TRUE

Convenience macro to return Py_True from a function. Example:

Py_RETURN_FALSE

Convenience macro to return 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:
Example:

Best Practices

Use macros for simple returns:
Use PyBool_FromLong for computed results:
Don’t compare by reference unless needed:
Don’t create new boolean objects:

See Also

Integer Objects

Booleans are a subclass of int

Object Protocol

Truth value testing

Reference Counting

Immortal objects