Created
May 13, 2016 10:45
-
-
Save milliams/3984c2a876c8fd5e227a189f952d9e0f to your computer and use it in GitHub Desktop.
Add static variables into a Python function with a decorator
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
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