Am I right in understanding that decorators are a form of closures as the decorator function is returning the function declared inside it ?
@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.
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.Of course ultimately a word can mean different things; did you have a more specific question about what a decorator or a closure does?