3 ms·
Are decorators more than syntactic sugar for functions that take functions?
by kaens 18y ago
Are decorators more than syntactic sugar for functions that take functions?
- irrelative 18y agoDelicious, delicious syntactic sugar :)
- llimllib 18y ago# No. This code: @decorate def foo(self): frobnicate() #is exactly equivalent to: def foo(self): frobnicate() foo = decorate(foo) http://www.python.org/dev/peps/pep-0318/ http://www.python.org/dev/peps/pep-0318/
- gaius 18y agoYeah, but that's really clunky when you want to do @this @that @the_other def foo(self): frobnicate() This is what Java people call "aspect oriented programming" and get all excited about, but to us it's no big deal :-)
- schtog 18y agoUseful example, adding memoization without rewriting the actual function, just add @decoratorname above the function. class memoize: def __init__(self, function): self.function = function self.memoized = {} def __call__(self, *args): try: return self.memoized[args] except KeyError: self.memoized[args] = self.function(*args) return self.memoized[args] @memoize def fib(n)
- anamax 18y ago2.5 supported function decorators, which this is. (The decorator has always been a callable, so the above class has always been legal.) 2.6 supports decorators for other things, including classes.