【发布时间】:2020-03-04 01:33:23
【问题描述】:
我的代码在python2.7 中运行良好,但在python 3 中失败
functools.lru_cache(maxsize=32) 从 python 2 到 python 3 的任何更改。
我得到的错误是我的configparser对象在缓存functools.lru_cache它说
TypeError: unhashable type: 'ConfigParser'
想了解 'functools.lru_cache' 从 python 2 和 python 3 的变化吗?
#CONFI FILE
[translate]
api_url = https://url
api_version = version_num
api_key = key_value
#code goes here
import functools
from configparser import ConfigParser as SafeConfigParser
config = SafeConfigParser()
path ="./conf/services.ini"
config.read(path)
@functools.lru_cache(maxsize=32)
def build_api_params_key(config):
"""Build the api url and return with key."""
api_url = config.get('translate', 'api_url')
api_version = config.get('translate', 'api_version')
api_key = config.get('translate', 'api_key')
full_api_url = api_url + api_version
return api_key
【问题讨论】:
-
cache = {}cache_get = cache.get....make_key = _make_key# 从函数中构建一个键argumentskey = make_key(args, kwds, typed)result = cache_get(key, sentinel)错误是因为while缓存解析器对象被用作dict 键,并且由于该对象不可散列,因此会引发错误。如果我们有一个不可散列的对象作为参数,还有其他使用 functools.lru_cache 的方法吗? -
Python 2.7 does not have
functools.lru_cache. Python 3.2 新增。 -
是的,Python 2.7 使用
functools32.lru_cache我尝试使用functools.lru_cache,因为functools32在python 3 中被重命名为functools。 -
functools32未重命名为functools。functools32是后来的functools功能的backport。
标签: python python-3.x python-2.7 functools