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

北慕城南 提交于 2019-12-03 04:50:32

问题


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

回答1:


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

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



回答2:


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



回答3:


Another way:

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



回答4:


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.




回答5:


Just do this:

True = bool(1)

Or, because booleans are essentially integers:

True = 1



回答6:


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__


来源:https://stackoverflow.com/questions/30563716/how-do-i-undo-true-false-in-python-interactive-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!