gpt4 book ai didi

python - 如何使用 python 装饰器修复 "NoneType"错误?

转载 作者:行者123 更新时间:2023-12-01 00:47:38 29 4
gpt4 key购买 nike

我正在使用装饰器进行 LRU(最近最少使用)缓存来存储最近使用的本地化,但是当我调用函数从 .json 文件读取它时,我收到“NoneType”错误

def loc_cache(func):
loc_cache.locale = {} # {lang:(local, count)} local:dict
loc_cache.MAXLENGTH = 5
def wrapper(key):
print(key) #this function wasn't called
if key not in loc_cache.locale.keys():
try:
locale = read_locale(key)
loc_cache.locale[key] = (locale, 1)
wrapper.locale = locale
except KeyError:
key = "en" # set default locale
wrapper(key)
else:
locale, count = loc_cache.locale[key]
loc_cache.locale[key] = (locale, count+1)
wrapper.locale = locale
return wrapper.locale

@loc_cache
def read_locale(key):
locale = read_json("./config/locale.json", key)
return locale

def auth(user:User):
locale = read_locale(user.locale)
print(locale["auth"])
return

u = User(1) # __init__ takes 1 for id
u.locale = "en"
auth(u)

我希望它会返回存储在 .json 文件中的“en”中的短语,但它说

Traceback (most recent call last):
File "main.py", line 61, in <module>
auth(u)
File "main.py", line 52, in auth
locale = read_locale(user.locale)
TypeError: 'NoneType' object is not callable

最佳答案

您没有从装饰器返回包装函数,因此 Python 像往常一样返回 None 并在您执行 read_locale(user.locale) 时尝试调用它。您需要:

def loc_cache(func):
loc_cache.locale = {} # {lang:(local, count)} local:dict
loc_cache.MAXLENGTH = 5
def wrapper(key):
print(key) #this function wasn't called
if key not in loc_cache.locale.keys():
try:
locale = read_locale(key)
loc_cache.locale[key] = (locale, 1)
wrapper.locale = locale
except KeyError:
key = "en" # set default locale
wrapper(key)
else:
locale, count = loc_cache.locale[key]
loc_cache.locale[key] = (locale, count+1)
wrapper.locale = locale
return wrapper.locale
return wrapper
# Here ^^^^

关于python - 如何使用 python 装饰器修复 "NoneType"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56824493/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com