- Django Design Patterns and Best Practices
- Arun Ravindran
- 125字
- 2021-06-25 21:32:09
Cached properties
Each time we call a property, we are recalculating a function. If it is an expensive calculation, we might want to cache the result. This way, the next time the property is accessed, the cached value is returned:
from django.utils.functional import cached_property #... @cached_property def full_name(self): # Expensive operation e.g. external service call return "{0} {1}".format(self.firstname, self.lastname)
The cached value will be saved as a part of the Python instance in memory. As long as the instance exists, the same value will be returned.
As a fail-safe mechanism, you might want to force the execution of the Expensive operation to ensure that stale values are not returned. In such cases, set a keyword argument such as cached=False to prevent returning the cached value.
推薦閱讀
- Raspberry Pi for Python Programmers Cookbook(Second Edition)
- HTML5移動(dòng)Web開發(fā)技術(shù)
- PyTorch自動(dòng)駕駛視覺(jué)感知算法實(shí)戰(zhàn)
- Django:Web Development with Python
- Instant Ext.NET Application Development
- C語(yǔ)言程序設(shè)計(jì)實(shí)驗(yàn)指導(dǎo) (第2版)
- Java Web開發(fā)就該這樣學(xué)
- Java程序員面試筆試寶典(第2版)
- HTML5開發(fā)精要與實(shí)例詳解
- 從零開始:UI圖標(biāo)設(shè)計(jì)與制作(第3版)
- Node.js 6.x Blueprints
- Mastering Unreal Engine 4.X
- Magento 2 Developer's Guide
- C語(yǔ)言進(jìn)階:重點(diǎn)、難點(diǎn)與疑點(diǎn)解析
- Java EE應(yīng)用開發(fā)及實(shí)訓(xùn)