How do I undo True = False in python interactive mode?

PythonBooleanPython 2.x

Python Problem Overview


So I tried the "evil" thing Ned Deily mentioned in his answer here. Now I have that the type True is now always False. How would I reverse this within the interactive window?

Thing to not do:

True = False

Since True has now been completely overridden with False, there doesn't seem to be an obvious way to back-track. Is there a module that True comes from that I can do something like:

True = <'module'>.True

Python Solutions


Solution 1 - Python

You can simply del your custom name to set it back to the default:

>>> True = False
>>> True
False
>>> del True
>>> True
True
>>>

Solution 2 - Python

This works:

>>> True = False
>>> True
False
>>> True = not False
>>> True
True

but fails if False has been fiddled with as well. Therefore this is better:

>>> True = not None

as None cannot be reassigned.

These also evaluate to True regardless of whether True has been reassigned to False, 5, 'foo', None, etc:

>>> True = True == True   # fails if True = float('nan')
>>> True = True is True
>>> True = not True or not not True
>>> True = not not True if True else not True
>>> True = not 0

Solution 3 - Python

Another way:

>>> True = 1 == 1
>>> False = 1 == 2

Solution 4 - Python

For completeness: Kevin mentions that you could also fetch the real True from __builtins__:

>>> True = False
>>> True
False
>>> True = __builtins__.True
>>> True
True

But that True can also be overriden:

>>> __builtins__.True = False
>>> __builtins__.True
False

So better to go with one of the other options.

Solution 5 - Python

Just do this:

True = bool(1)

Or, because booleans are essentially integers:

True = 1

Solution 6 - Python

Solutions that use no object literals but are as durable as 1 == 1. Of course, you can define False once True is defined, so I'll supply solutions as half pairs.

def f(): pass
class A(): pass
True = not f()
False = A != A

False = not (lambda:_).__gt__(_)
True = not (lambda:_).__doc__

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhortaView Question on Stackoverflow
Solution 1 - Pythonuser2555451View Answer on Stackoverflow
Solution 2 - Python101View Answer on Stackoverflow
Solution 3 - PythonRoberto BonvalletView Answer on Stackoverflow
Solution 4 - PythonsimonwoView Answer on Stackoverflow
Solution 5 - PythonLoovjoView Answer on Stackoverflow
Solution 6 - PythonPythonNutView Answer on Stackoverflow