How to see if you're in debug mode

Sometimes I only want print statements to execute if I’m debugging a program, and I don’t want them to execute for the user. Here’s how to tell if you are in debug mode.

import sys
has_trace = hasattr(sys, 'gettrace') and sys.gettrace() is not None
has_breakpoint = sys.breakpointhook.__module__ != "sys"
isdebug = has_trace or has_breakpoint
print(f"{has_trace=} {has_breakpoint=} {isdebug=}")

I put this right at the beginning of my program after any import statements.

Changing the behavior of your program when inside a debugger seems like a recipe for great frustration.

I would recommend using the logging module instead. Then you can set the level at which specific messages are shown (e.g. debug, info, warning, error).

Yes, logging levels is the best practice for turning on and off debug logs.

Personally I use logging/print to debug python and never use a debugger.

1 Like