我使用 dict
作为短期缓存。我想从字典中获取一个值,如果字典中没有那个键,请设置它,例如:
val = cache.get('the-key', calculate_value('the-key'))
cache['the-key'] = val
如果 'the-key'
已经在 cache
中,则第二行不是必需的。有没有更好、更短、更具表现力的成语?
最佳答案
可读性很重要!
if 'the-key' not in cache:
cache['the-key'] = calculate_value('the-key')
val = cache['the-key']
如果你真的喜欢单线:
val = cache['the-key'] if 'the-key' in cache else cache.setdefault('the-key', calculate_value('the-key'))
另一种选择是在缓存类中定义__missing__
:
class Cache(dict):
def __missing__(self, key):
return self.setdefault(key, calculate_value(key))
关于python - 在 python 字典中获取和设置值的最佳习惯用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11152559/