__debug__ always True

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
hlovatt
Posts: 12
Joined: Thu Aug 15, 2019 3:52 am

__debug__ always True

Post by hlovatt » Thu Aug 22, 2019 8:12 am

If I run:

Code: Select all

import micropython
micropython.opt_level(3)
print('Opt level: {}, Debug: {}'.format(micropython.opt_level(), __debug__))
On:

Code: Select all

MicroPython v1.11-167-g331c224e0 on 2019-07-21; PYBv1.1 with STM32F405RG
I get:

Code: Select all

Opt level: 3, Debug: True
I was expecting 2 and above to set `__debug__ = False`.

Any idea what I'm doing wrong?

hlovatt
Posts: 12
Joined: Thu Aug 15, 2019 3:52 am

Re: __debug__ always True

Post by hlovatt » Thu Aug 22, 2019 8:22 am

Just noticed that it works if I type the code in at the REPL but not when run from the file system :(

User avatar
jimmo
Posts: 791
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia

Re: __debug__ always True

Post by jimmo » Thu Aug 22, 2019 9:21 am

Hi,

The behaviour of __debug__ is a bit subtle. It's handled by the lexer, so when __debug__ appears in your code, MicroPython effectively replaces it with True or False depending on the current value -- before executing any code. So setting opt_level in the same script won't change the value in the current script.

The documentation says "If *level* is given then this function sets the optimisation level for subsequent compilation of scripts"

Every line that you execute in the REPL is a new compilation.

If you want opt_level to take effect for your main.py, set it in boot.py.

hlovatt
Posts: 12
Joined: Thu Aug 15, 2019 3:52 am

Re: __debug__ always True

Post by hlovatt » Fri Aug 23, 2019 2:28 am

Thanks, that explains what is going on. I didn't get any of the subtlety from the documentation! Thanks again.

Post Reply