Is there only one True and one False object in Python?

情到浓时终转凉″ 提交于 2019-12-11 03:17:33

问题


I know that Python guarantees that there is only one instance of NoneType, the None object, so that you can safely use is None to test if something equals None.

Is there an equivalent guarantee for bool True and False (i.e. that there is only one instance of each)?

If not, why not?

EDIT: In particular, I've noticed that (n+0) is (0+n) gives True for n in range(-5, 257) and False otherwise. In other words, zero, the first 256 positive and the first 5 negative integers seem to be pre-cached and are not instanced again. I am guessing that that's a choice of the interpreter (CPython, in my case) and not a specification of the language. And bool derives from int, so I still have to wonder about what expectations I can have with other interpreters.

EDIT: To clarify, since this seems to have generated a lot of confusion, my intention is not to test the boolean interpretation of a value. For that I would never use is True or is False. My intention is to be able to tell apart False from everything else, in a variable that can have values of several types including empty strings, zeros, and None, and similarly for True. I'm myself an experienced programmer, of the kind who cringes when I see "if booleanvar == True".

NOTE ON DUPLICATES: The questions this one was alleged to be a duplicate of (this and this) don't answer this question; they merely state that bool is a subclass of int that differ mainly in their repr, not if True and False are guaranteed to be unique.

Also, note that it's not a question about what the names True and False are bound to, but about the instances of the class bool.


回答1:


From the docs (https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy):

Booleans

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects.

There are only two objects, any computation producing a boolean will produce one of those two existing objects:

>>> (1 == 1) is True
True
>>> (1 == 0) is False
True



回答2:


The bool type has only two instances, True and False. Furthermore, it can't be subclassed, so there's no way to create a derived class that can have additional instances.

But even though it's guaranteed, there's seldom a good reason to rely upon it. You should usually use if x rather than if x is True, and avoid situations where you need to distinguish True from other truthy values or False from other falsy values.



来源:https://stackoverflow.com/questions/24842852/is-there-only-one-true-and-one-false-object-in-python

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