在 Python 交互模式下如何撤消 True = False?

因此,我尝试了奈德 · 戴利在他的答案 给你中提到的“邪恶”的东西。现在我知道类型 True 现在总是 False。如何在交互式窗口中逆转这种情况?

不该做的事:

True = False

因为 True 现在已经被 False 完全覆盖,所以似乎没有明显的回溯方法。有没有一个 True 来自的模块,我可以这样做:

True = <'module'>.True
6100 次浏览

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

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

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

Just do this:

True = bool(1)

Or, because booleans are essentially integers:

True = 1

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.

Another way:

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

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__