What are the true and false criteria for a python object? [duplicate]
Asked Answered
A

2

8

I have 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 occur?

Assyriology answered 29/4, 2017 at 6:27 Comment(0)
G
11

All objects1 in Python have a truth value:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None

  • False

  • zero of any numeric type, for example, 0, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.

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


1 … unless they have a __bool__() method which raises an exception, or returns a value other than True or False. The former is unusual, but sometimes reasonable behaviour (for example, see the comment by user2357112 below); the latter is not.

Grouping answered 29/4, 2017 at 6:46 Comment(1)
Well, usually, anyway. This is one of the parts where the docs gloss over the more subtle aspects of operator overloading. You can make a class where trying to take its truth value throws a TypeError, and this is sometimes reasonable, such as for NumPy arrays.Seeder
G
2

When you type if a:, it is equivalent to if bool(a):. So it doesn't mean that a is True, only that a's representation as a boolean value is True.

Generally speaking bool is a subclass of int, where True == 1 and False == 0.

Growler answered 29/4, 2017 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.