Sometimes we’d like to have a class that is tolerant of attribute accesses that weren’t anticipated at class design time, returning a default ‘None’ value for an uninitialized attribute. Using defaultdict to override the `__dict__` attribute makes this very easy:
from collections import defaultdict class X(object): def __init__(self): self.__dict__ = defaultdict(lambda : None) def __getattr__(self, attr): return self.__dict__[attr]
Now we can initialize an object with some attributes, but access others and get back the default None:
x = X() x.color = "RED" x.size = 6 print x.color print x.size print x.material
RED 6 None
Of course, this defeats a key validation feature in Python, so you’ll need to take extra care that you specify attributes correctly.