Created
April 15, 2016 15:30
-
-
Save romuald/58e2c7fb6659b305ee702b2f336e4ea0 to your computer and use it in GitHub Desktop.
Abusing python defaults
This file contains hidden or 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
# Abusing python default initialization to create static variables | |
def pompom(arg, static={'counter': 0}): | |
static['counter'] += 1 | |
print("Yup %d, %d") % (arg, static['counter']) | |
pompom(8) | |
pompom(42) | |
""" | |
Yup 8, 1 | |
Yup 42, 2 | |
""" | |
class Static(object): | |
def __init__(self, **kwargs): | |
for k, v in kwargs.items(): | |
setattr(self, k, v) | |
def another(arg, static=Static(counter=0)): | |
static.counter += 1 | |
print("Yup (again) %d, %d") % (arg, static.counter) | |
another(8) | |
another(80) | |
""" | |
Yup (again) 8, 1 | |
Yup (again) 80, 2 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment