|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +""" |
| 5 | +Lazily-evaluated property pattern in Python. |
| 6 | +
|
| 7 | +https://en.wikipedia.org/wiki/Lazy_evaluation |
| 8 | +http://stevenloria.com/lazy-evaluated-properties-in-python/ |
| 9 | +""" |
| 10 | + |
| 11 | + |
| 12 | +deflazy_property(fn): |
| 13 | +"""Decorator that makes a property lazy-evaluated.""" |
| 14 | +attr_name='_lazy_'+fn.__name__ |
| 15 | + |
| 16 | +@property |
| 17 | +def_lazy_property(self): |
| 18 | +ifnothasattr(self, attr_name): |
| 19 | +setattr(self, attr_name, fn(self)) |
| 20 | +returngetattr(self, attr_name) |
| 21 | +return_lazy_property |
| 22 | + |
| 23 | + |
| 24 | +classPerson(object): |
| 25 | +def__init__(self, name, occupation): |
| 26 | +self.name=name |
| 27 | +self.occupation=occupation |
| 28 | + |
| 29 | +@lazy_property |
| 30 | +defrelatives(self): |
| 31 | +# Get all relatives, let's assume that it costs much time. |
| 32 | +relatives="Many relatives." |
| 33 | +returnrelatives |
| 34 | + |
| 35 | + |
| 36 | +defmain(): |
| 37 | +Jhon=Person('Jhon', 'Coder') |
| 38 | +print("Name:{0} Occupation:{1}".format(Jhon.name, Jhon.occupation)) |
| 39 | +print("Before we access `relatives`:") |
| 40 | +print(Jhon.__dict__) |
| 41 | +print("Jhon's relatives:{0}".format(Jhon.relatives)) |
| 42 | +print("After we've accessed `relatives`:") |
| 43 | +print(Jhon.__dict__) |
| 44 | + |
| 45 | + |
| 46 | +if__name__=='__main__': |
| 47 | +main() |
| 48 | + |
| 49 | +### OUTPUT ### |
| 50 | +# Name: Jhon Occupation: Coder |
| 51 | +# Before we access `relatives`: |
| 52 | +#{'name': 'Jhon', 'occupation': 'Coder'} |
| 53 | +# Jhon's relatives: Many relatives. |
| 54 | +# After we've accessed `relatives`: |
| 55 | +#{'_lazy_relatives': 'Many relatives.', 'name': 'Jhon', 'occupation': 'Coder'} |
0 commit comments