好吧,我认为如果 python 是惰性语言,那是可能的,但是您的代码应该更改为
def f(x):
c = common_helper_function(x)
return a_complex_function(x,c), another_complex_function(x,c)
在python中,这不是真的
def test1():
print ' simple function'
return 1
print 'Calling simple function:'
_ = (lambda : test1())()
print 'Calling simple function again:'
_ = (lambda : test1())()
output:
Calling simple function:
simple function # evaluated once
Calling simple function again:
simple function # evaluated twice
为了提高性能,我建议您查看两个概念:
记忆- 您可以将函数调用的结果保存在字典中,并且在计算后不再重新计算。对于lru_cache
的模块中有装饰器functools
(对于python 2.7,您可以下载functools32)。这是一个例子
from functools32 import lru_cache
@lru_cache(maxsize=10)
def test2():
print ' cashed function'
return 1
print 'Calling cashed function:'
_ = (lambda : test2())()
print 'Calling cashed function again:'
_ = (lambda : test2())()
output:
Calling cashed function:
cashed function # evaluated once
Calling cashed function again:
# not evaluated twice
懒惰的评价。尝试获取函数结果时,函数的每个结果都会评估一次,然后存储。因此,在您的情况下,直到使用存储函数调用结果的变量才对其进行评估。对于 python 2.7,您可以使用Alberto Bertogli 的lazy.py:
import lazy
@lazy.lazy
def test3():
print ' lazy function'
return 1
print 'Calling lazy function:'
b = (lambda : test3())()
print 'Calling cashed function again:'
b = (lambda : test3())()
print 'Trying to get results:'
print b
output:
Calling lazy function:
Calling cashed function again:
Trying to get results:
lazy function # evaluated
1