safex
safex

Reputation: 2514

Unexpected PyCharm run vs debug behavior for __debug__

I have the following python code:

def main():
    if __debug__:
        print("debug mode")
    else:
        print("non debug")


if __name__ == '__main__':
    main()

No matter whether I run the file or debug it, it always prints "debug mode". this is not what I would have expected. My debug block is computationally costly, so I Would prefer to only run it on my development machine if I am in debug mode in pycharm (and never in prod).

Upvotes: 1

Views: 177

Answers (1)

Dorian Turba
Dorian Turba

Reputation: 3755

My debug block is computationally costly, so I Would prefer to only run it on my development machine if I am in debug mode in pycharm (and never in prod).

This is exactly why the optimization flag exist in Python.

Use optimization flag

Because __debug__ is true when you don't use the optimization flag.

Add this to the run configuration "Interpreter options": -O

You can get the same behavior with python in CLI:

$ python file.py
debug mode
$ python -O file.py
Non debug

More details on -O flag: What is the use of the "-O" flag for running Python?

Upvotes: 1

Related Questions