For some reason a lot of types are implicitly convertible to boolean values, despite Python’s “be explicit” guideline. Anyway…
Is it idiomatic to make custom classes also implicitly convertible to bool, where appropriate? If yes, what function should I (re)define? In my specific case, I have an Image class; I want to make it convertible to bool such that it is True when it is holds data loaded from somewhere (a file), and False otherwise.
This can be idiomatic; e.g., container object should test false when they are empty. You should define
__nonzero__in Python 2.x and__bool__in Python 3 to do the conversion. When writing code targeting Python 2 and 3, define both.However, in keeping with the “explicit is better than implicit” guideline, you might instead want to just say
if img.is_loaded():instead. The main reason__nonzero__/__bool__exists is for containers, which is reflected in its description in The Python Data model: “When this method is not defined,__len__()is called, if it is defined, and the object is considered true if its result is nonzero.” So it’s really shorthand forlen(obj) == 0, perhaps implemented with a faster check.