0

我有一个 python 函数,它根据传递的参数缓存结果。问题是,fval()可以根据其他因素返回不同的值。但是test()仍然给我发送了陈旧的价值观。我如何确保参数v从中获取最新值fval()

@cached(60*5)
def test(a,v=fval()):
  print "inside function"
  return a,v

r = test(2)
inside test function
print r
(2, 5)

print fval()
7

r = test(2) . #This time I am expecting v to be 7, but it isnt
print r 
(2,5)

我期待 r 打印 (2,7) 代替。如何确保将最新值作为参数发送到缓存函数?

4

2 回答 2

0

当针对 Python 中的所有函数评估函数本身时,会评估可选值。通常的解决方案是提供一个不代表任何内容的值,然后检查它:

@cached(60*5)
def test(a, v=None):
    if v is None:
        v = fval()

    print "inside function"
    return a, v

如果在那之后,您还希望cached对最终值执行操作,fval()而不是缺少第二个参数,则需要执行以下操作:

@cached(60*5)
def _test(a, v):
    print "inside function"
    return a, v

def test(a, v=None):
    if v is None:
        v = fval()

    return _test(a, v)
于 2019-02-27T03:44:22.740 回答
0

这是因为这条线:

def test(a,v=fval()):

在 Python 中,默认参数在函数定义处解析一次。

您可能需要执行以下操作:

def test(a, v=None):
    if v is None:
        v = fval()

    # the rest here
于 2019-02-27T03:44:33.733 回答