News for hackers. Stuff that matters.
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.

There are no comments on this comment yet.