How to check if I'm in debug mode

I’m on Windows 11, using Python 3.14.0 with Windows Terminal. I would like to check if I’m using a debugger (I use python -m pdb file.py) and set a isdebug flag so if isdebug flag is True I can print debug messages to the console or to my error file. I don’t need to check for pdb specifically, I just need to know if I’m in any debugger. I figured that would be easier.

This example used to work in Python 3.12 but does not work in Python 3.14.

import sys
# This always returns False in Python 3.14.
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 also tried these 2 other methods I got from AI. They also return False when I’m in the debugger.

if hasattr(sys, "gettrace") and sys.gettrace() is not None:
    print("Debugger/tracer detected (likely pdb if launched with -m pdb).")
else:
    print("No debugger/tracer detected")

dbgflag = hasattr(sys, "gettrace") and sys.gettrace() is not None
print(f"dbgflag={dbgflag}")

Does anyone have a solution for Python 3.14?

Thank you! You are all so awesome!

After a little more research I found that this works in Python 3.14.

def debugrunning():
    r'''Check to see if we are in debug mode. 
    This is for Python 3.14+ only as some internal things have changed.
    See https://peps.python.org/pep-0669/
    
    For Python 3.11 and less use this: 
    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=}")
    
    In: nothing
    Out: Boolean, True if we're in debug mode.

    Usage: debugflag = debugrunning()
    '''
    procname = libfilename + ":debugrunning:" 

    # Newer CPython debugging path (PEP 669 infrastructure via sys.monitoring) https://peps.python.org/pep-0669/
    mon = getattr(sys, "monitoring", None)
    if mon is not None:
        try:
            # Returns a string name if DEBUGGER_ID is in use, else None.
            if mon.get_tool(mon.DEBUGGER_ID) is not None:
                return True
        except Exception:
            # If monitoring exists but behaves unexpectedly, fall through.
            pass

    # Older / alternate path: classic tracing
    gettrace = getattr(sys, "gettrace", None)
    if gettrace is not None and gettrace() is not None:
        return True

    return False

debugflag = debugrunning()
print(f"debugflag={debugflag}")

I hope this will help others. :slight_smile: