[英]making function lazy in Python
I want to write a wrapper function for eternity
that will make it behave as if it's being lazily evaluated. 我想为eternity
编写一个包装函数,使它的行为就像被懒惰地求值一样。 In other words, its functionality should be made identical to that of the function lazyeternity
below. 换句话说,其功能应与下面的功能lazyeternity
相同。 I have this function packageN
that takes a function and packages it into a lambda--or at least I think it does. 我有这个函数packageN
,它接受一个函数并将其打包为lambda,或者至少我认为这样做。 (Packaging lazyeternity
inside a lambda delayed its evaluation in the call of etest
.) How can I modify packageN
so that eternity = packageN(eternity)
can mirror the behavior of lazyeternity
? (将lazyeternity
打包在lazyeternity
延迟了etest
的调用。)如何修改packageN
以便eternity = packageN(eternity)
可以反映lazyeternity
的行为?
def eternity():
return eternity()
# How can I create a wrapper function for eternity...
# that will make it behave identical to this function?
def lazyeternity():
return lambda: lazyeternity()
def packageN(f):
return lambda *x: f(*x)
def etest(x, y):
return x
eternity = packageN(eternity)
# I want these both to return 4.
# Currently only the first one returns 4,...
# because the second one evaluates the eternity()...
# parameter forever. I want to delay the evaluation...
# of the parameter.
print etest(4, lazyeternity())
print etest(4, eternity())
The difference between lazyeternity
and eternity
as returned by packageN
is that calling lazyeternity
returns a lambda, whereas eternity
is a lambda which, when called, runs forever. packageN
返回的lazyeternity
和eternity
之间的区别是,调用lazyeternity
返回一个lambda,而eternity
是一个lambda,当被调用时,它将永远运行。
To make packageN
return something that acts like lazyeternity
, make it 要使packageN
返回类似于lazyeternity
行为,请使其
def packageN(f):
return lambda: lambda *x: f(*x)
To make both eternity
work, simply remove the ()
. 要使两个eternity
起作用,只需删除()
。 You want to return a function, not the evaluation of a function (infinite loop). 您想返回一个函数,而不是函数的求值(无限循环)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.