Skip to content

Instantly share code, notes, and snippets.

@Marrin Marrin/closure.py
Created Sep 14, 2016

Embed
What would you like to do?
"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
You can’t perform that action at this time.