This week I learned 49
This week I learned that a trailing comma can lead to unexpected results.
I’ve been working through the Advent of Code each night in python3. Day 4’s problem was the most involved so far. When I submitted part 2 I was greeted with the all-too-familiar “that’s the wrong answer” screen. I checked my code, fixed up a few errors and submitted again. Wrong answer still. I scanned through my code again. Wrote assertions for all of their tests and then I saw it: a trailing comma turned a False value True.
>>> def f():
... return False
...
>>> assert f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> def g():
... return False,
...
>>> assert g()
>>>
The trailing ,
turns False into (False,) – that is, a tuple with one
element. The docs say this about truthiness.
By default, an object is considered true unless its class defines either a
__bool__()
method that returns False or a__len__()
method that returns zero, when called with the object. 1 Here are most of the built-in objects considered false:
Sure enough, a one-element tuple defines a __len__()
method that returns 1.