I Like Programming

Who says Python doesn’t have function static variables?

If you want to store internal state in a python function, most people would say you need to create a class and use class or instance attributes. Of course you don’t. Python 3 introduces “nonlocal” as a keyword for creating static variables, but you can already make them without this help.

In fact, you might even create them accidentally, due to this weird behavior with default arguments. Python only evaluates default arguments once, so if your default argument is mutable complex type, you have yourself some internal state.

>>> def counter(count=[0]):
...   count[0] += 1
...   return count[0]
... 
>>> counter()
1
>>> counter()
2
>>> counter()
3

Well, that’s kind of a hack. A better way to do this is to use function attributes. Yes, functions can have attributes, just like classes.

def counter():
  counter.count += 1
  return counter.count
counter.count = 0