closure = decorator?

Chris Angelico rosuav at gmail.com
Thu Oct 10 10:03:04 EDT 2013


On Fri, Oct 11, 2013 at 12:51 AM, Tim <jtim.arnold at gmail.com> wrote:
> I've read a couple of articles about this, but still not sure.
> When someone talks about a closure in another language (I'm learning Lua on the side), is that the same concept as a decorator in Python?

No, they're quite different. A decorator (let's look at function
decorators; classes can have them too, and they work pretty much the
same way) is syntactic sugar for this:

def func(args):
    blah blah blah
func = decorator(func)

You can do all sorts of things with that. Even stupid things:

>>> @print
def foo():
pass

<function foo at 0x00F5D8A0>
>>> foo is None
True

Using print as a decorator does work, though hardly usefully :)

A closure, on the other hand, is a function that has some extra context:

def outer(x):
    x += 1
    def inner():
        return x
    return inner

The function inner() "knows" its context. When it's called, it'll use
the same value for x that would have been used in the outer function,
even though it's a separate function:

>>> foo = outer(5)
>>> foo()
6

The terminology is that inner() "closes over" x, if I have that
correct (I've not been all that big in functional programming and
lambda calculus). Someone will correct me if I'm not.

It's very common for a decorator to use closures, but the two are
completely different. They're no more connected than, say, for loops
and lists. They just happen to work well together.

Closures in other languages will, as far as I know, be the same thing
as closures in Python. (And their presence and functionality in
JavaScript leaves me wondering why on earth the 'this' reference can't
be considered "closed over" in the same way. But that's hardly the
worst of the language's warts.)

ChrisA



More information about the Python-list mailing list