简体   繁体   English

使函数在Python中变得懒惰

[英]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返回的lazyeternityeternity之间的区别是,调用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM