Lazy Initialize Data Attributes in Python

Suppose we want to create a “lazy” data attributes ( “instance variables” in Smalltalk, or “data members” in C++) in a Python Class. We may required to use getattr to customize attribute access.

Here is a example

class MyData(object):
def __getattr__(self, attr):
if attr == "pool" and attr not in self.__dict__:
self.__dict__[attr] = ThreadPool(10) # lazy initialize here
return self.__dict__[attr]

We may create a new instance using d = MyData(), and once we call d.pool, it will initialize a ThreadPool at this moment.