4 ms·
Am I right in understanding that decorators are a form of closures as the decorator function is returning the function declared inside it ?
by bigb9320 12y ago
Am I right in understanding that decorators are a form of closures as the decorator function is returning the function declared inside it ?
- alangpierce 12y agoDecorators typically use closures (including in this case), but they're really just syntax sugar for transforming one function into a different one with the same name. This code: @d def foo(): ... is equivalent to this code: def foo(): ... foo = d(foo) (You should think of a Python "def" statement as an action that creates a function and assigns it to a variable, like "foo" in this case. Since functions are first-class values, they can be sent into other functions and assigned again, which is why this works.) But yeah, if you're implementing a decorator (a function from function to function, like "d" above), you can declare an inner function and immediately return it, and that inner function will act as a closure (it will have access to variables in the outer scope). You can take that approach in other situations as well, not just with decorators.
- deleted 12y ago[deleted]
- Rapzid 12y agoThey don't have to be: http://stackoverflow.com/questions/4912116/closure-vs-anonymous-function-difference http://stackoverflow.com/questions/4912116/closure-vs-anonym...
- ekimekim 12y agoAs a followup to the sibling comment, note that closures aren't the only way to achieve the same effect, for example: class MyDecorator(object): def __init__(self, func): self.func = func def __call__(self, one, two, three): # do stuff return self.func(three, two, one) ie. you can just as easily use a class instance to store your state, instead of a closure. I routinely use both methods, depending on which is more useful at the time.
- lmm 12y agoOnly in a trivial syntactic sense. They're better understood (IMO) as combinators, though even that isn't absolutely accurate. Of course ultimately a word can mean different things; did you have a more specific question about what a decorator or a closure does?