I was recently reading some code online, and saw this block:
if 'True' not in globals():
globals()['True'] = not None
globals()['False'] = not True
What is happening here? Why would True
ever not be in globals? I've never come across anything like this during my ~10 years as a professional python programmer!
That code is super duper old, targeting compatibility with Python 2.2. Back before Python 2.3, there was no bool
type and no built-in True
or False
. You can also see a from __future__ import generators
future statement up at the top, because generators existed in 2.2, but the syntax had to be turned on explicitly, because the Python dev team didn't want to introduce a new keyword (yield
) without a transition period.
Incidentally, this code's author got the compatibility logic wrong. The built-in True
would have been in the __builtin__
module, not globals()
, so this code is checking in the wrong place. Fortunately, there are few consequences to accidentally adding redundant bindings for True
and False
to globals()
, as long as you don't do something like True = False
(which was possible in Python 2).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With