3 ms·
I still don't fully understand decorators, but it's definitely true that implementing context managers with decorators is much more succinct and straightforward
by BrandonM 18y ago
I still don't fully understand decorators, but it's definitely true that implementing context managers with decorators is much more succinct and straightforward than manually writing __enter__ and __exit__ methods. And context managers are definitely a win.
- kaens 18y agoAre 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.