Check if program runs in Debug mode

The following works for me in VSCode:

import sys 

def debugger_is_active() -> bool:
    """Return if the debugger is currently active"""
    return hasattr(sys, 'gettrace') and sys.gettrace() is not None

Tested on PyCharm 2021.3.2:

def is_debug():
    import sys

    gettrace = getattr(sys, 'gettrace', None)

    if gettrace is None:
        return False
    else:
        v = gettrace()
        if v is None:
            return False
        else:
            return True

According to the documentation, settrace / gettrace functions could be used in order to implement Python debugger:

sys.settrace(tracefunc) 

Set the system’s trace function, which allows you to implement a Python source code debugger in Python. The function is thread-specific; for a debugger to support multiple threads, it must be registered using settrace() for each thread being debugged.

However, these methods may not be available in all implementations:

CPython implementation detail: The settrace() function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations.

You could use the following snippet in order to check if someone is debugging your code:

import sys


gettrace = getattr(sys, 'gettrace', None)

if gettrace is None:
    print('No sys.gettrace')
elif gettrace():
    print('Hmm, Big Debugger is watching me')
else:
    print("Let's do something interesting")
    print(1 / 0)

This one works for pdb:

$ python -m pdb main.py 
> /home/soon/Src/Python/main/main.py(3)<module>()
-> import sys
(Pdb) step
> /home/soon/Src/Python/main/main.py(6)<module>()
-> gettrace = getattr(sys, 'gettrace', None)
(Pdb) step
> /home/soon/Src/Python/main/main.py(8)<module>()
-> if gettrace is None:
(Pdb) step
> /home/soon/Src/Python/main/main.py(10)<module>()
-> elif gettrace():
(Pdb) step
> /home/soon/Src/Python/main/main.py(11)<module>()
-> print('Hmm, Big Debugger is watching me')
(Pdb) step
Hmm, Big Debugger is watching me
--Return--
> /home/soon/Src/Python/main/main.py(11)<module>()->None
-> print('Hmm, Big Debugger is watching me')

And PyCharm:

/usr/bin/python3 /opt/pycharm-professional/helpers/pydev/pydevd.py --multiproc --qt-support --client 127.0.0.1 --port 34192 --file /home/soon/Src/Python/main/main.py
pydev debugger: process 17250 is connecting

Connected to pydev debugger (build 143.1559)
Hmm, Big Debugger is watching me

Process finished with exit code 0