CSC/ECE 517 Spring 2014/ch1 1w1l m
Design Patterns Involving Closures
Background
What is a closure?
Very simply, a closure is a function that can use a reference to a variable that was valid within the scope that the closure was defined, but need not be in-scope where the closure is called. A quick example is very illustrative.
>>> def closure_builder():
... message = "String, in-scope where closure is defined"
... def closure(new_msg=None):
... if new_msg is None:
... print message
... else:
... print new_msg
... return closure
...
>>> default_closure = closure_builder()
>>> del closure_builder # Without closures, the message var would be gone now
>>> default_closure() # But it's still here!
String, in-scope where closure is defined
>>> default_closure("I can do this too, although it's bit obvious")
I can do this too, although it's bit obvious
Examples
Narration
Links to Important Terms
References
<references />