Python lazy evaluator

后端 未结 7 2280
心在旅途
心在旅途 2020-12-19 05:14

Is there a Pythonic way to encapsulate a lazy function call, whereby on first use of the function f(), it calls a previously bound function g(Z) an

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 05:50

    Try using this decorator:

    class Memoize:
        def __init__ (self, f):
            self.f = f
            self.mem = {}
        def __call__ (self, *args, **kwargs):
            if (args, str(kwargs)) in self.mem:
                return self.mem[args, str(kwargs)]
            else:
                tmp = self.f(*args, **kwargs)
                self.mem[args, str(kwargs)] = tmp
                return tmp
    

    (extracted from dead link: http://snippets.dzone.com/posts/show/4840 / https://web.archive.org/web/20081026130601/http://snippets.dzone.com/posts/show/4840) (Found here: Is there a decorator to simply cache function return values? by Alex Martelli)

    EDIT: Here's another in form of properties (using __get__) http://code.activestate.com/recipes/363602/

提交回复
热议问题