如何在不执行两次函数的情况下检查python函数输出并将其赋给变量?

2024-10-01 00:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我想做以下事情

def calculate_something_extremally_resource_consuming():
    # execute some api calls and make insane calculations
    if calculations_sucessfull:
        return result

同时在项目的其他地方:

if calculate_something_extremally_resource_consuming():
    a = calculate_something_extremally_resource_consuming()
    etc...

看起来重载函数会被调用两次,这真的很糟糕。我可以想象的另一个选择是:

a = calculate_something_extremally_resource_consuming()
if a:
    etc...

也许有更优雅的方式?你知道吗


Tags: andapiexecuteifdefetcsome事情
2条回答

^{}有时可以帮助您:

Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.

>>> from functools import lru_cache
>>> from time import sleep
>>> @lru_cache()
... def expensive_potato():
...     print('reticulating splines...')
...     sleep(2)
...     return 'potato'
... 
>>> expensive_potato()
reticulating splines...
'potato'
>>> expensive_potato()
'potato'

这是python3.2中的新特性。如果您使用的是老Python,那么很容易编写自己的decorator。你知道吗

如果您使用的是类的方法/属性,^{}很有用。你知道吗

在某些语言中,可以将变量指定为条件块的一部分,但在Python中这是不可能的(请参见Can we have assignment in a condition?

相关问题 更多 >