简体   繁体   中英

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. In other words, its functionality should be made identical to that of the function lazyeternity below. I have this function packageN that takes a function and packages it into a lambda--or at least I think it does. (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 ?

    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.

To make packageN return something that acts like lazyeternity , make it

def packageN(f):
    return lambda: lambda *x: f(*x)

To make both eternity work, simply remove the () . You want to return a function, not the evaluation of a function (infinite loop).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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