The other day I stumbled upon Python __debug__ and I thought I would share some interesting things I learned about it.
What is python __debug__?
It is a constant that Python uses to determine if calls to assert should result in code being generated. If you have the -O optimization flag set, then assert calls will not be “triggered” in your code, even if the condition it is testing is true.
Interesting fact: according to the documentation it is one of two constants that will raise a SyntaxError exception if you attempt to assign something to it. (The other constant that does this is None.)
For example, in python you can do this:
And that is totally legal in Python 2.x. (Python 3 wisely does not allow this!) I would not recommend doing this, as your co-workers will hunt you down to express their “displeasure”. But if you try that with __debug__ or None, you’ll get an error:
Normally I’m not a fan of these types of language tricks, but this looked pretty cool to me and I thought I would share. I do find it interesting that in Python 3 they have True and False locked down to be true constants. Honestly, I thought there would be more language keywords that would be protected like that.