News for hackers. Stuff that matters.
Re:Things which aren't magic – Flask and app.route by bigb9320 on Monday December 29, 2014 @03:11AM (#8808914)
Am I right in understanding that decorators are a form of closures as the decorator function is returning the function declared inside it ?
Re:Things which aren't magic – Flask and app.route by alangpierce on Monday December 29, 2014 @03:45AM (#8808977)
Decorators 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.

Re:Things which aren't magic – Flask and app.route by ekimekim on Monday December 29, 2014 @03:58AM (#8809017)
As 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.
Re:Things which aren't magic – Flask and app.route by lmm on Monday December 29, 2014 @08:35AM (#8809683)
Only 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?

Re:Things which aren't magic – Flask and app.route by Rapzid on Monday December 29, 2014 @03:51AM (#8808996)