Possibility and Probability

A Python programmer with a personality thinking about space exploration

9 January 2017

python __debug__

by nickadmin

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: [caption id=”attachment_987” align=”aligncenter” width=”229”]How to assign false to true in python Totally legal. Not smart, but legal.[/caption] 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: [caption id=”attachment_986” align=”aligncenter” width=”380”]can't assign things to __debug__ or None The only two “true” constants in python[/caption] 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.