CSC/ECE 517 Spring 2014/ch1 1w1l m: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
(Added basic definition of a closure)
Line 3: Line 3:
== Background ==
== Background ==
=== What is a closure? ===
=== What is a closure? ===
According to Peter Norvig's <ref>[http://norvig.com/design-patterns/design-patterns.pdf Design Patterns in Dynamic Languages]</ref>, closures can be considered "behaviors with attached state data and without the overhead of classes." This is the inverse of objects, which are state data with behaviors attached, and closures encapsulate local state variables.
 
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.
 
<code>
>>> 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
</code>


== Examples ==
== Examples ==

Revision as of 06:55, 23 February 2014

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 />