How to Debug Print Behind a DEBUG Environment Flag in Python
Create a debug_print function that only outputs when the DEBUG environment variable is set to a truthy value like 1, true, yes, or on.
Python code
13 linesimport os
def debug_print(*args, **kwargs):
"""Print only when DEBUG environment variable is set to a truthy value."""
if os.environ.get("DEBUG", "").lower() in ("1", "true", "yes", "on"):
print(*args, **kwargs)
if __name__ == "__main__":
# Example usage: run as `DEBUG=1 python script.py` to see debug output
debug_print("This only appears when DEBUG is set")
print("This always appears")
Output
When run without DEBUG set:
This always appears
When run with DEBUG=1:
This only appears when DEBUG is set
This always appears
How it works
The debug_print function reads the DEBUG environment variable using os.environ.get() with a default empty string. It then converts it to lowercase and checks against a set of common truthy string values. This approach makes the flag easy to set in any environment — local dev, CI, or containers — without changing code. The function mirrors print()'s signature with *args, **kwargs, so you can pass separators, end characters, and file handles exactly as you would with a normal print. Using a dedicated function keeps debug statements in production code but silently disables them unless explicitly enabled.
Common mistakes
- Forgetting to import `os` at the top of the module
- Checking only for `'1'` or `'true'` but missing common values like `'yes'` or `'on'`
- Using case-sensitive comparison, so `'True'` fails the check
- Putting debug prints in production paths without a fallback to a logging library
Variations
- Use `logging` module with `logging.basicConfig(level=logging.DEBUG)` and set `debug_print` to call `logging.debug`
- Check for the variable with `if os.getenv('DEBUG'):` for simpler truthiness (treats only non-empty strings as true)
Real-world use cases
- Adding verbose tracing in scraper scripts that run in CI, so logs stay clean unless DEBUG=1 is set.
- Instrumenting a serverless function to dump request/response payloads only when a debugging stage is enabled.
- Keeping diagnostic print statements in a data pipeline that operators can switch on during incidents without redeploying code.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.