if x calls a method¶
Level: 201 · for Python programmers
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The bullets below are the questions the finished page has to answer.
One line: if x: calls x.__bool__(), falls back to x.__len__(), and takes the answer to be True when the class defines neither — so every empty container is false, an object of a class you wrote is true until you say otherwise, and if result: on a function that returns 0 or [] on success is a bug that never raises.
What the finished page has to answer¶
- The rule, measured on the built-ins:
0,0.0,'',b'',[],{},set(),range(0),Nonefalse; everything else true, including'0',' 'and[0]. - A class with neither method is always true, so a
Metres(0)object passesif m:; a class with__len__is false when empty;__bool__must return abool, and returning anything else isTypeError. if x is not Noneagainstif x, and the function that returns0on success.andandorreturn an operand, not abool, sox or defaultreplaces a legitimate0and'', andall([])isTrue.datetime.time(0)was false before 3.5, dated, as the one case the core team reversed.- Where the rule reaches:
while x,not x,filter(None, xs), and a comprehension'sif.
See also¶
isis not==: whyNoneis tested withis- Truth value testing ↗ in the library reference, and
object.__bool__↗ ifexpressions ↗ in the Rust library, whereiftakes abooland nothing else