Created
April 22, 2019 15:33
-
-
Save acoomans/9bd0238c60bbb9f69d10954301c6a05b to your computer and use it in GitHub Desktop.
Python decorators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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