Real-life example – lazily evaluated attributes

One example usage of descriptors may be to delay initialization of the class attribute to the moment when it is accessed from the instance. This may be useful if the initialization of such attributes depends on the global application context. The other case is when such initialization is simply expensive, but it is not known whether it will be used anyway when the class is imported. Such a descriptor could be implemented as follows:

class InitOnAccess: def __init__(self, klass, *args, **kwargs): self.klass = klass self.args = args self.kwargs = kwargs self._initialized = None def __get__(self, instance, owner): if self._initialized is None: print('initialized!') self._initialized = self.klass(*self.args, ...

Get Expert Python Programming - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.