Created
September 14, 2016 15:25
-
-
Save Marrin/e00fa440a313e5eb4ee7b1cc857797a4 to your computer and use it in GitHub Desktop.
"Real" closure in Python 2.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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