functools - Higher-order functions and operations on callable objects#

functools 是 Python 标准库中对于函数式编程的支持. 因为函数在 Python 中是 first class object, 本身也是对象, 也可以被当做参数传递. 所以就衍生出了很多技巧.

cached_property#

这是在 3.8 之后才加入的. 用于解决 @property 装饰器包装的方法每次调用都要重新计算的问题.

Example: remove cached property cache.
 1# -*- coding: utf-8 -*-
 2
 3"""
 4Example: remove cached property cache.
 5"""
 6
 7import dataclasses
 8from functools import cached_property
 9
10
11@dataclasses.dataclass
12class Person:
13    first_name: str
14    last_name: str
15
16    @cached_property
17    def full_name(self):
18        print("call full name")
19        return f"{self.first_name} {self.last_name}"
20
21    def reset_full_name_cache(self):
22        try:
23            del self.full_name
24        except AttributeError:
25            pass
26
27
28p = Person("John", "Doe")
29p.reset_full_name_cache()
30print(p.full_name)
31print(p.full_name)
32
33p.reset_full_name_cache()
34print(p.full_name)

Reference: