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:
>>> 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:
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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Using Python Optional Arguments When Defining Functions (Tutorial)
- Defining Your Own Python Function (Tutorial)
- Python Booleans: Leveraging the Values of Truth (Course)
- Defining Python Functions With Optional Arguments (Course)
- Using Python Optional Arguments When Defining Functions (Quiz)
- Defining and Calling Python Functions (Course)
- Defining Your Own Python Function (Quiz)
- Defining and Calling Python Functions (Quiz)
By Leodanis Pozo Ramos • Updated Jan. 8, 2026