1

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).

safex
  • 2,398
  • 17
  • 40

1 Answers1

1

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?

Dorian Turba
  • 3,260
  • 3
  • 23
  • 67
  • I see I phrased the question poorly, but you answered what I asked. What I Really look for is whether I can change the default way in which pycharm runs (i.e. have the `-O` flag added by default): https://stackoverflow.com/questions/75384689/pycharm-change-default-run-behaviour-to-include-o-flag – safex Feb 08 '23 at 10:50
  • `-O` should be in prod like scripts only, in pycharm, you should run in debug mode, no? – Dorian Turba Feb 08 '23 at 10:55