0

I'm trying wrap my head around python decorators so I borrowed this supposedly fastest memoization implementation :

class memoize(dict):
      def __init__(self, func):
          self.func = func
      def __call__(self, *args):
          return self[args]
      def __missing__(self, key):
          result = self[key] = self.func(*key)
          return result

>>> @memoize
... def foo(a, b):
...     return a * b
>>> foo(2, 4)
8
>>> foo
{(2, 4): 8}

Piece of cake but then I came to know about functools wraps. The doc says it:

This is a convenience function for invoking update_wrapper() as a function decorator when defining a wrapper function. It is equivalent to partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated).

When to use it and when not to use it ? Could anyone tell me If I've to use the above class memoization using that functools.wraps how would I change it ? Thanks in advance!

d-coder
  • 12,813
  • 4
  • 26
  • 36
  • Have you read [this](https://stackoverflow.com/questions/308999/what-does-functools-wraps-do) already? Also [this](https://stackoverflow.com/questions/15357776/what-is-the-difference-between-functools-wraps-and-update-wrapper). Does it help answer your question? – idjaw Jun 30 '17 at 14:41
  • you should probably use functools.lru_cache in the first place –  Jun 30 '17 at 14:41
  • @idjaw Then the right way of doing a decorator is using wraps ? – d-coder Jun 30 '17 at 14:58

0 Answers0