Skip to content

Instantly share code, notes, and snippets.

@romuald
Created April 15, 2016 15:30
Show Gist options
  • Save romuald/58e2c7fb6659b305ee702b2f336e4ea0 to your computer and use it in GitHub Desktop.
Save romuald/58e2c7fb6659b305ee702b2f336e4ea0 to your computer and use it in GitHub Desktop.
Abusing python defaults
# 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