Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading