Boolean flag

A Boolean flag is a variable or function argument you set to True or False to control behavior. You’ll often see Boolean flags used to toggle options, enable features, or track state during a computation.

When you add a Boolean flag to a function, favor clear, keyword-only arguments so call sites stay readable. Avoid positional Boolean arguments because calls like func(x, True) don’t explain intent.

Example

Here’s an example of a built-in function using a Boolean flag to flip behavior:

Python
>>> sorted([3, 1, 2])
[1, 2, 3]

>>> sorted([3, 1, 2], reverse=True)
[3, 2, 1]

Design your own flags as clear, keyword-only arguments with a sencible default:

Python
def save(path, *, overwrite=False):
    if not overwrite and Path(path).exists():
        raise FileExistsError(f"{path!r} already exists")
    # Write the file here...

# Usage
save("report.txt", overwrite=True)  # Explicit intent
save("draft.txt")  # Rely on the default (False)

If you find yourself adding multiple flags to one function, consider refactoring. For example, split into separate functions with focused behavior, or replace Boolean flags with an Enum or a small strategy object when there are more than two modes.

Tutorial

Python Booleans: Use Truth Values in Your Code

In this tutorial, you'll learn about the built-in Python Boolean data type, which is used to represent the truth value of an expression. You'll see how to use Booleans to compare values, check for identity and membership, and control the flow of your programs with conditionals.

intermediate python stdlib

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 8, 2026