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.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 12 views 0 copies

Python code

13 lines
Python 3.9+
import 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

stdout
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

  1. Use `logging` module with `logging.basicConfig(level=logging.DEBUG)` and set `debug_print` to call `logging.debug`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.