September 2021
Intermediate to advanced
152 pages
3h 5m
English
| Tip 77 | Grasp What Is Truth |
★★★2.7, 3.4+ The Python concept of truth and falseness goes far beyond the boolean constants True and False. Typically, a “naturally empty” object is interpreted as false: None, 0, 0j, 0.0, an empty list, an empty tuple, an empty dictionary, an empty set—in other words, something that either is nothing, is numerically zero, or has the length of zero.
You can decide how to interpret an arbitrary object’s boolean value by redefining its method __len__:
| | class GlassIsHalfEmpty: |
| | def __init__(self, mood): |
| | self.mood = mood |
| | def __len__(self): |
| | return 1 if self.mood == 'pessimist' else 0 |
| | |
| | bool(GlassIsHalfEmpty('pessimist')) |
| => | True |
| | bool(GlassIsHalfEmpty('optimist')) |
| => | False |
The plethora ...
Read now
Unlock full access