Python: static variable decorator

前端 未结 8 907

I\'d like to create a decorator like below, but I can\'t seem to think of an implementation that works. I\'m starting to think it\'s not possible, but thought I would ask yo

8条回答
  •  猫巷女王i
    2021-01-06 16:11

    When you need to save state between invocations of a function, you are almost always better off using a generator/coroutine or an object. Since you want to use "bare" variable names, then you'll want the coroutine version.

    # the coroutine holds the state and yields rather than returns values
    def totalgen(x=0, y=0, z=0):
        while True:
           a, b, c = (yield x, y, z)
           x += a
           y += b
           z += c
    
    # the function provides the expected interface to callers
    def runningtotal(a, b, c, totalgen=totalgen()):
        try:
            return totalgen.send((a, b, c))    # conveniently gives TypeError 1st time
        except TypeError:
            totalgen.next()                    # initialize, discard results
            return totalgen.send((a, b, c))
    

    The result is a function that accumulates totals of the three values passed to it, exactly as if it had static variables, but the accumulators are plain old local variables in what is essentially an infinite generator.

提交回复
热议问题