学习路径:https://www.aiuai.cn/aifarm1963.html
from functools import lru_cache
from pydantic import BaseSettings
n = 0
class Settings(BaseSettings):
environment: str = "development"
@lru_cache(maxsize=128, typed=False) # 被 lru_cache 修饰的函数在被相同参数调用的时候,后续的调用都是直接从缓存读结果,而不用真正执行函数。
def get_settings(): # 如果调用两次传的参数不一样,无法缓存
global n
settings = Settings()
print(f"Loaded settings for environment: {settings.environment}")
n += 1
return settings
def action_a():
print(get_settings().environment)
def action_b():
print(get_settings().environment)
if __name__ == "__main__":
action_a()
action_b()
print(n)
输出:
Loaded settings for environment: development
development
development
1
可以看出函数调用了两次,但是n只增加了一次。去掉lru_cache
装饰器,n就是2了