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

From Expertiza_Wiki
Jump to navigation Jump to search
(Added basic definition of a closure)
(Somewhat better closure example)
Line 4: Line 4:
=== What is a closure? ===
=== 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.
Very simply, a closure is a function that can use 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>
<code>
  >>> def closure_builder():
  #!/usr/bin/env python
...    message = "String, in-scope where closure is defined"
...    def closure(new_msg=None):
# Define a function that makes use of closures
...        if new_msg is None:
def closure_builder(message="Default"):
...            print message
    def closure():
...        else:
        # Message is in-scope here
  ...            print new_msg
        print message
  ...    return closure
    return closure
  ...
   
  >>> default_closure = closure_builder()
  # Build two functions
  >>> del closure_builder  # Without closures, the message var would be gone now
  default_closure = closure_builder()
  >>> default_closure()  # But it's still here!
  custom_closure = closure_builder("Custom")
String, in-scope where closure is defined
   
  >>> default_closure("I can do this too, although it's bit obvious")
# In case you're not convinced
  I can do this too, although it's bit obvious
del closure_builder
  # Call the closures you built
  default_closure()  # Amazingly, prints "Default"
  custom_closure()  # Amazingly, prints "Custom"
</code>
</code>



Revision as of 07:11, 23 February 2014

Design Patterns Involving Closures

Background

What is a closure?

Very simply, a closure is a function that can use 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.

#!/usr/bin/env python

# Define a function that makes use of closures
def closure_builder(message="Default"):
    def closure():
        # Message is in-scope here
        print message
    return closure

# Build two functions
default_closure = closure_builder()
custom_closure = closure_builder("Custom")

# In case you're not convinced
del closure_builder

# Call the closures you built
default_closure()  # Amazingly, prints "Default"
custom_closure()  # Amazingly, prints "Custom"

Examples

Narration

Links to Important Terms

References

<references />