Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are True and False being set in globals by this code?

Tags:

python

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!

like image 577
user31415629 Avatar asked Jun 17 '19 14:06

user31415629


1 Answers

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).

like image 70
user2357112 supports Monica Avatar answered Nov 07 '22 11:11

user2357112 supports Monica