|
| 1 | + |
| 2 | +============ |
| 3 | + Truthiness |
| 4 | +============ |
| 5 | + |
| 6 | +.. admonition:: Verdict |
| 7 | + |
| 8 | + Python programmers have an engrained habit |
| 9 | + of refactoring Boolean tests into their briefest possible form |
| 10 | + when checking for the number zero, for the empty string, |
| 11 | + or for an empty list. |
| 12 | + While clearly Pythonic — |
| 13 | + the Python Tutorial itself recommends the practice — |
| 14 | + this practice is overused. |
| 15 | + More explicit tests for zero or empty length |
| 16 | + serve to document the type of an argument, |
| 17 | + and can make Python code more rich in expressing the type it expects. |
| 18 | + |
| 19 | +Programmers who prefer their code to be brief rather than explicit |
| 20 | +are delighted to learn that Python’s ``if`` and ``while`` |
| 21 | +not only accept the objects ``True`` and ``False``, |
| 22 | +but also objects as diverse as integers, strings, |
| 23 | +tuples, lists, and dictionaries. |
| 24 | +Numbers are false if they are zero; |
| 25 | +sequences are false if their ``len()`` is zero; |
| 26 | +and the singleton object ``None`` is false. |
| 27 | + |
| 28 | +The Python data model |
| 29 | +invites user classes to opt into the same system |
| 30 | +by defining the ``__bool__()`` dunder method, |
| 31 | +which is invoked by ``if`` and ``while`` |
| 32 | +and also by the ``bool()`` builtin. |
| 33 | + |
| 34 | +The Problem |
| 35 | +=========== |
| 36 | + |
| 37 | +.. todo - add link to Naming of Ducks |
| 38 | + |
| 39 | + or add this whole doc to a “making types explicit” doc? |
| 40 | + |
| 41 | +The question of type — |
| 42 | +of whether a name references an integer, or list, or class instance — |
| 43 | +is rarely a problem in small Python projects |
| 44 | +that are reasonably careful with naming |
| 45 | +and whose code can be read at a single sitting. |
| 46 | +Python is a language whose programmers |
| 47 | + |
| 48 | +.. testcode:: |
| 49 | + |
| 50 | + def acceleration(, subscriptions, height, gravity, active_subscriptions): |
| 51 | + if len(users) == 0: |
| 52 | + return |
| 53 | + if active_subscriptions == 0: |
| 54 | + raise SubscriptionRequired() |
| 55 | + while if n > 0: |
| 56 | + foo(users) |
| 57 | + |
| 58 | + |
| 59 | +might quibble about ``== 0`` |
0 commit comments