Re: Memoization and encapsulation




just> I actually prefer such a global variable to the default arg
just> trick. The idiom I generally use is:

just> _cache = {}
just> def func(x):
just> result = _cache.get(x)
just> if result is None:
just> result = x + 1 # or a time consuming calculation...
just> _cache[x] = result
just> return result

None of the responses I've seen mention the use of decorators such as the
one shown here:

http://wiki.python.org/moin/PythonDecoratorLibrary

While wrapping one function in another is obviously a bit slower, you can
memoize any function without tweaking its source.

Skip
.



Relevant Pages

  • Re: Death to tuples!
    ... >>> Not at definion time. ... >> The idiom to get a default argument evaluated at call time with the ... def f: ... > if arg is None: ...
    (comp.lang.python)
  • Re: Death to tuples!
    ... >> Not at definion time. ... > The idiom to get a default argument evaluated at call time with the ... def f: ... if arg is None: ...
    (comp.lang.python)
  • Re: Reading a class-file and calling it at runtime.
    ... but here is a trick i ... use when rails mess with my requires. ... def require_relative *args ...
    (comp.lang.ruby)
  • Re: An efficient, pythonic way to calculate result sets
    ... objects in the outer set, and the amount of items in the choices sets ... for arg in args: ... def choose_first: ... 'Assume a choice of a first object' ...
    (comp.lang.python)
  • Re: Guidos new method definition idea
    ... self.value = arg ... def self.othermethod: ... an object attribute, I have to use a dummy name, like the following: ... Altough I'm not a huge fan of decorators, this would be more in line ...
    (comp.lang.python)