When you’re writing Python tutorials, you have to use Monty Python references. It’s the law. On the 40th anniversary of the release of Monty Python’s Life of Brian, I wanted to share this example that I made for collections.defaultdict
that doesn’t fit in the tutorial I’m writing. It comes as homage to the single Eric the Half a Bee.
from collections import defaultdict
class HalfABee:
def __init__(self):
self.is_a_bee = False
def value(self):
self.is_a_bee = not self.is_a_bee
return "Is a bee" if self.is_a_bee else "Not a bee"
>>> eric = defaultdict(HalfABee().value, {})
>>> print(eric['La di dee'])
Is a bee
>>> print(eric['La di dee'])
Not a bee
Dictionaries that can return different values for the same key are a fine example of Job Security-Driven Development.