0

I am too paranoid to use other datatype than bool for if-statement. For example, I already know that non-empty list is interpreted as true, no matter what is inside.

123 if [True] else 456
# 123

123 if [False] else 456
# 123

123 if [] else 456
# 456

However, I just noticed that numpy.ndarray acts differently:

123 if np.array([True]) else 456
# 123

123 if np.array([False]) else 456
# 456

123 if np.array([]) else 456
# 456

My lack of true understanding is preventing me from using these concise syntax confidently. Can I someone point me to/give a definitive documentation on this? Maybe Python actually checks for an implementation of some '__xxx__' function on the object?

Apiwat Chantawibul
  • 1,271
  • 1
  • 10
  • 20
  • 2
    Single element arrays have the truthy value of that element. But multi-element arrays raise an 'ambiguity' error when the context expects a single boolean value. In general do not use arrays in an 'if'. – hpaulj Jul 20 '21 at 03:04
  • Thank you for pointing me to \_\_bool\_\_, now I got the mechanism which is clearly explained here: https://docs.python.org/3/reference/datamodel.html#object.__bool__ – Apiwat Chantawibul Jul 20 '21 at 03:10
  • 1
    Also https://docs.python.org/3/reference/expressions.html#booleans – hpaulj Jul 20 '21 at 03:29
  • `np.array([]).__bool__()` gives a DeprecationWarning:g in recent versions. `np.array([1,3]).__bool__()` gives the Ambiguity error. – hpaulj Jul 20 '21 at 03:34

0 Answers0