Created
April 27, 2020 12:39
-
-
Save Susensio/dbf6954a148271d9dbb00408f5d19ac6 to your computer and use it in GitHub Desktop.
Python static variable decorator for functions
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
# Source: https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/279586#279586 | |
def static_vars(**kwargs): | |
def decorate(func): | |
for k in kwargs: | |
setattr(func, k, kwargs[k]) | |
return func | |
return decorate | |
@static_vars(counter=0) | |
def foo(): | |
foo.counter += 1 | |
print(f"Counter is {foo.counter}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, it works. however, if foo.counter =+ 1, it doesn't work.