...">

What are the true and false criteria for a python object?

I've seen the following cases:

>>> def func(a):
...     if a:
...         print("True")
...
>>> a = [1, 2, 3]
>>> func(a)
True
>>> a == True
False

      

Why does this difference arise?

+3


source to share


2 answers


All 1 objects in Python have a truth value :

Any object can be tested for true, for use in a state if

or while

or as an operand for the logical operations below. The following values ​​are considered false:

  • None

  • False

  • zero any numeric type, for example 0

    , 0.0

    , 0j

    .
  • Any empty sequence, for example ''

    , ()

    , []

    .
  • any empty display eg {}

    .

  • instances of custom classes, if the class defines a method, __bool__()

    or __len__()

    when that method returns an integer 0 or a bool value False

    .

All other values ​​are considered true, so objects of many types are always true.




1 ... unless they have a method __bool__()

that throws an exception, or returns a value other than True

or False

. The first is unusual, but sometimes reasonable behavior (for example, see user2357112's comment below); the latter is not.

+6


source


When entered, if a:

it is equivalent if bool(a):

. Thus, this does not mean that a is True

, only the presentation a

as a boolean value True

.



Generally speaking, bool

is a subclass int

where True == 1

and False == 0

.

+2


source







All Articles