Pages

Sunday, December 30, 2012

Closure in Python - example

Closure is a "function (code block)" with a "referencing environment". I interpret it as a function pointer with free variables. In Python terms, a variable defined in an enclosing function is a free variable inside any nested functions.
In this example, printer is a closure as it points to a code block with a free variable of "msg". The variable msg is closed over the printer() function.
def make_printer(msg):
    def printer():
        print msg
    return printer

printer = make_printer('Foo!')
printer()
This printer method is not a closure but nested function, as in this case "msg" variable is nothing but a local variable that is not "closed".
def make_printer(msg):
    def printer(msg=msg):
        print msg
    return printer

printer = make_printer("Foo!")
printer() # "Foo!"
printer("Hello") # --> "Hello"

References

No comments:

Post a Comment