Skip to content

Instantly share code, notes, and snippets.

@acoomans
Created April 22, 2019 15:33
Show Gist options
  • Save acoomans/9bd0238c60bbb9f69d10954301c6a05b to your computer and use it in GitHub Desktop.
Save acoomans/9bd0238c60bbb9f69d10954301c6a05b to your computer and use it in GitHub Desktop.
Python decorators
def cache(f):
'''Memorizes the return value for a function regardless arguments beyond the first one.'''
class cache:
UNSET = 'unset'
def __init__(self, f):
self.f = f
self.ret = cache.UNSET
def __call__(self, *args, **kwargs):
if self.ret == cache.UNSET:
self.ret = self.f(*args, **kwargs)
return self.ret
return cache(f)
def count(f):
'''Count and pass as argument the number of times the function was called.'''
class counter:
def __init__(self, f):
self.f = f
self.c = 0
def __call__(self, *args, **kwargs):
ret = self.f(*args, **dict(kwargs, count=self.c))
self.c = self.c + 1
return ret
return counter(f)
def memoize(f):
'''Memorizes the return value for a function for given arguments.'''
class memodict(dict):
def __init__(self, f):
self.f = f
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = self.f(*key)
return ret
return memodict(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment