Skip to content

Instantly share code, notes, and snippets.

@Susensio
Created April 27, 2020 12:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Susensio/dbf6954a148271d9dbb00408f5d19ac6 to your computer and use it in GitHub Desktop.
Save Susensio/dbf6954a148271d9dbb00408f5d19ac6 to your computer and use it in GitHub Desktop.
Python static variable decorator for functions
# 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}")
@frankzecaiwang
Copy link

Thanks, it works. however, if foo.counter =+ 1, it doesn't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment