Skip to content

Instantly share code, notes, and snippets.

@ksamuel
Created December 22, 2011 15:12
Show Gist options
  • Save ksamuel/1510635 to your computer and use it in GitHub Desktop.
Save ksamuel/1510635 to your computer and use it in GitHub Desktop.
Closure python en lecture seule
# this works (like javascript)
def test(value): # functions that returns a function
def closure(plus): # function got 'value' in a closure
return value + plus
return closure
func = test(5) # create a function that always add 5
print func(2)
# display 7
# But this doesn't work (but does ion JS):
def test(value):
def closure(plus):
value = value + plus # modify the closure
return value
return closure
func = test(5)
print func(2)
# this trigger this weird error:
# UnboundLocalError
# Traceback (most recent call last)
# /home/kevin/<ipython-input-12-0f5d249a85b0> in <module>()
# ----> 1 test(5)(2)
# /home/kevin/<string> in closure(plus)
# UnboundLocalError: local variable 'value' referenced before assignment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment