Bool as int? How python evaluates

In [1]: a=5

In [2]: print(["is odd", "is even"][a % 2 == 0])
is odd

In [3]: [a%2 == 0]
Out[3]: [False]

      

What I understood is a % 2 == 0

evaluated as True

or False

.

So, if it's True, then this is equivalent to 1 and using the indices of the list to be printed 'is even'

.

I read this one and found out what bool

is the instance int

.

So, when used as in an index bool

, it evaluates to its equivalent ie 0

or 1

.

My question

Based on intuition, we can know if it will be int

orbool

But how does Python know? Does it have any criteria for when to use bool

and when to use how int

? Anything from Python3 documentation would be appreciated.

+3


source to share


2 answers


This is not guaranteed in Python 2.x, as it is possible to reassign True

and False

. However, even if this happens, boolean True

and boolean False

are still correctly returned for comparison.

In Python 3.x True and False are keywords and will always be equal to 1

and 0

.

Under normal circumstances in Python 2 and always in Python 3:

False

an object has a type bool

that is subclassed int

:

 object
   |
  int
   |
  bool

      



This is the only reason your example works ['zero', 'one'][False]

. It won't work on an object that is not a subclass of integer, as list indexing only works on integers or objects that define a method __index__

(thanks to mark-dickinson).

Edit:

This applies to the current version of Python and the version of Python 3. The docs for Python 2.6 and docs for Python 3 say:

There are two types of integers: [...] Integers (int) [...] Booleans (bool) and in a boolean subsection:

Booleans: they represent the truth values ​​False and True [...] Boolean values ​​behave like the values ​​0 and 1, respectively, in almost all contexts, the exception is that when converted to a string, the strings "False" or "True", respectively.

So booleans are explicitly treated as integers in Python 2.6 and 3.

+6


source


The instances bool

, True

and False

, are separated from the instances int

, 0

and 1

. The point is that bools behave like integers in many contexts. For example, True+True

which is equal to 2. However, if we check whether they are the same object, we see that it is not: True is 1

. On the other hand, it is true that True is True

. Here is an example that behaves like integers but prints True and False and is compared to differently is

.

class Bool(int):
    def __repr__(self):
        return 'True' if self==1 else 'False'

      



https://docs.python.org/3/library/stdtypes.html#bltin-boolean-values

0


source







All Articles