Skip to content

Instantly share code, notes, and snippets.

@milliams
Created May 13, 2016 10:45
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 milliams/3984c2a876c8fd5e227a189f952d9e0f to your computer and use it in GitHub Desktop.
Save milliams/3984c2a876c8fd5e227a189f952d9e0f to your computer and use it in GitHub Desktop.
Add static variables into a Python function with a decorator
def static_vars(**kwargs):
"""
Decorate a function and provide it with some static variables.
>>> @static_vars(counter=0)
... def foo():
... foo.counter += 1
... return foo.counter
>>> foo()
1
>>> foo()
2
"""
def decorate(func):
func.__dict__.update(kwargs)
return func
return decorate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment