Python’s Function Static Variable

So you want a variable that stays between different calls of a function. Not the sexiest thing ever but always handy in small programs.

There’s tons of ways of doing this. You can embark on a quest to find the meaning of Pythonic or take this method that’s relatively simple:

def a():
    if not hasattr(a, "b"): a.b = 0
    a.b += 1
    print a.b

Calling a(), you’ll get 1, 2, 3, …

Note attribute ‘b’ of ‘a’ does not exist until you declare it for a first time. My main preference here is that ‘static’ variables used this way does not spill onto the rest of your code. Also, it’s clean, no classes, no data structures.

Related posts:

  1. Django Compress Static Files and Compile CSS
  2. Sizing conflicts exist on the screen error in SAP