The Python Oracle

In Python how to recover from joke statements like True = False

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops

--

Chapters
00:00 In Python How To Recover From Joke Statements Like True = False
00:49 Answer 1 Score 3
00:59 Accepted Answer Score 3
02:07 Answer 3 Score 4
02:31 Thank you

--

Full question
https://stackoverflow.com/questions/1366...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27

#avk47



ANSWER 1

Score 4


They're not "global" variables as such - they're built-ins.... They're available in __builtin__ (no s) - and you can do what you will "for a joke". Note that doing this kind of thing is mostly for mocking/profilers and things of that kin...

And no, you can't do that in the 3.x series, because True and False are keywords, not (sort of) singletons like in 2.x




ANSWER 2

Score 3


If things aren't too bad, you could set True = __builtins__.True.




ACCEPTED ANSWER

Score 3


The way to "recover" from this is to not let it happen.

That said, you can always use the bool() type to access True and False again. (bool() always returns one of the two boolean singletons.)

Example:

>>> bool
<type 'bool'>
>>> bool(1)
True
>>> bool(1) is bool('true')
True
>>> True = False
>>> True
False
>>> True is False
True
>>> False is bool()
True
>>> True = bool(1)
>>> True is bool(1)
True
>>> True is False
False
>>> True is bool()
False
>>> bool()
False
>>> True is bool(2)
True
>>> True is bool('true')
True
>>> 

If this is a simple True = 'something' binding, then what happens is that a new name True is created in the current namespace--the __builtins__ module is not altered. In this case you can simply delete (unbind) the "True" name in your namespace. Then Python will use the one defined in __builtins__ again.

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> True is __builtins__.True
True
>>> True = 'redefined'
>>> __builtins__.True is True
False
>>> del True
>>> __builtins__.True is True
True

None of this is possible in Python 3 because True and False are no longer names (variables) but keywords.