logoalt Hacker News

nneonneoyesterday at 10:51 PM2 repliesview on HN

The __debug__ constant is really weird - any block of code guarded with `if __debug__:` will be entirely omitted from the bytecode under PYTHONOPTIMIZE=1. This and `assert` are the only two examples of real “conditional compilation” in Python. This is also the reason why you cannot assign to __debug__: doing so would make it possible to invalidate the compiler’s assumption about `if __debug__:` statements.


Replies

plant-ianyesterday at 10:57 PM

I honestly have never even heard of this constant and I feel like I've been using python for a pretty long time. Although maybe my memory for some things just gets garbage collected if I don't use it enough. Does it actually get used that often in real world code? Seems like it might be kind of risky.

show 3 replies
Numerloryesterday at 11:52 PM

If 0. Etc. are also compiled out, at compile time __debug__ is simply False or True and the existing optimization paths take care of it.

Assigning to __debug__ wouldn't do anything to the compiler as it never actually reads the variable, so assignment would just cause weirdness from other use