4

In Python the built in constant None is guaranteed to be singular. There is only one instance of it.

This is not the case for other built in types. Strings or numbers with the same contents are not unique. Two strings "a" and "a" are not unique but have different instances. The same goes for two numbers with identical internal values, say 1.0 and 1.0.

Are the built in Boolean constants True and False unique like None, or do they have different instances?

A specific example is:

value = 1 == 1

in this case is value the same instance as True?

M Wade
  • 177
  • 1
  • 11
  • 5
    "The values False and True will be singletons, like None." [PEP 285 § Specification](https://www.python.org/dev/peps/pep-0285/#specification) – eugenhu Feb 21 '18 at 03:08
  • You can use [`id`](https://docs.python.org/3/library/functions.html#id) to satisfy these questions. Look at `id(True)` and `id(1 == 1)` – Patrick Haugh Feb 21 '18 at 03:21
  • 2
    @PatrickHaugh that's never sufficient to answer a question like this. You don't want to know if they *can* be the same, you want to know if they're *guaranteed* to be the same. – Mark Ransom Feb 21 '18 at 03:50

1 Answers1

5

The constants True and False are unique, as the specification guarantees they are the only instances of bool. That is, if you have two variables which were both initialized with True or a true boolean expression such as 1 == 1,* then they will compare identical with is. The same is true for False.

However, True == 1 and True is not 1. This is because booleans are a subclass of int. Boolean values will never compare identical to "regular" integers with is, but the type difference is ignored for comparison with integers, floating point values, and other numeric types, as is standard behavior for the numeric hierarchy.

* Be careful with more elaborate boolean expressions. In particular, and and or always return one of their operands, and do not coerce to boolean (unless their operands are already booleans).

(Incidentally, Python contains exactly two other singletons in addition to True, False, and None, namely Ellipsis and NotImplemented. Each type object is also more or less unique; if you write x = int; y = int, then x and y will compare identical with is, because there is only one object which represents the int type. This can be used if you are creating your own type hierarchy and want to avoid having objects compare equal to their subclasses like booleans do with integers. In other cases, it is of marginal benefit compared to isinstance() or issubclass(), which better respect the Liskov substitution principle.)

Kevin
  • 28,963
  • 9
  • 62
  • 81