Skip to content

Instantly share code, notes, and snippets.

@Marrin
Created September 14, 2016 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Marrin/e00fa440a313e5eb4ee7b1cc857797a4 to your computer and use it in GitHub Desktop.
Save Marrin/e00fa440a313e5eb4ee7b1cc857797a4 to your computer and use it in GitHub Desktop.
"Real" closure in Python 2.x
#!/usr/bin/env python3
def make_counter(value):
def inc():
nonlocal value
value += 1
return value
def dec():
nonlocal value
value -= 1
return value
return inc, dec
# Without `nonlocal` Marcin's way (doesn't work):
def make_counter(value):
def inc(container=[value]):
container[0] += 1
return container[0]
def dec(container=[value]):
container[0] -= 1
return container[0]
return inc, dec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment