Skip to content

Instantly share code, notes, and snippets.

@santa4nt
Created August 29, 2014 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santa4nt/831c018927be421915e0 to your computer and use it in GitHub Desktop.
Save santa4nt/831c018927be421915e0 to your computer and use it in GitHub Desktop.
Python decorator to memoize functions.
import unittest
# a generic function decorator to memoize call results
class Memoize(object):
def __init__(self, func):
self.func = func
self._cache = {}
self._count = 0
@property
def count(self):
return self._count
def __call__(self, *args):
try:
return self._cache[args]
except KeyError:
value = self.func(*args)
self._cache[args] = value
self._count += 1
return value
@Memoize
def factorial(num):
if num in (0, 1):
return 1
return num * factorial(num - 1)
@Memoize
def fibonacci(num):
if num in (0, 1):
return num
return fibonacci(num - 1) + fibonacci(num - 2)
class MemoizeTest(unittest.TestCase):
def test_factorial(self):
self.assertEquals(120, factorial(5))
self.assertEquals(5, factorial.count)
def test_fibonacci(self):
self.assertEquals(144, fibonacci(12))
self.assertEquals(13, fibonacci.count) # without memoization: 465 calls would've been made!
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment