为什么总是计算默认值?

Why is the default value always computed?

假设我有一个字典 d,它有一个键 0 或一个键 1。我想为 x 分配值 d[0](如果存在)并且 d[1] 否则。我还想销毁密钥 0(如果存在)。我会写:

    x = d.pop(0,d[1])

但是 运行 这对于 d = {0:'a'} 会引发错误。

同样,假设我有一个接受关键字参数的函数 x。如果已经计算 x ,那么我想使用给定的值。否则,我需要计算它。

    import time
    def long_calculation():
        time.sleep(10)
        return 'waited'

    def func(**kwargs):
        x = kwargs.pop('x',long_calculation())
        return x

运行 f(x='test') 需要 10 秒。

我可以做类似的事情

    x = kwargs.pop('x',None)
    if x is None:
        x = long_calculation()

但这有点麻烦。

关于缓存函数结果,请查看functools.lru_cache。示例:

from functools import lru_cache
@lru_cache(maxsize=32)
def long_calculation():
    time.sleep(10)
    return 'waited'

第二次调用returns缓存值:

print(long_calculation()) # 10 seconds
print(long_calculation()) # instant

如果你只想短路 dict.pop() 我认为将它放在嵌套的 try 块中更直接。喜欢:

try: 
    d.pop(0)
except KeyError:
    try:
        d[1]
    except KeyError:
        <expensive value>