lundi 19 juillet 2021

Documentation on how non boolean datatypes are interpreted for if-statement

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?

Aucun commentaire:

Enregistrer un commentaire