Main Content

Static variables in Python?

Archive - Originally posted on "The Horse's Mouth" - 2012-08-29 17:58:36 - Graham Ellis

Each time you call a function, you start off with a fresh set of variables. That's usually exactly what you want, as you don't usually want one calculation to be influenced by the debris of the previous similar calculation.

In Python, you can define a variable as an attribute of the method (using methodname-dot in front of the name) so that it remains / is retained. That's the equivalent of marking a variable static in PHP.

Here's the code for a counter which keeps a tally of the number of times a method has been called:

  def tick():
    tick.count += 1


You'll either need to initialise the attribute outside the method (but after you have defined the method), or catch the exception that's thrown when you try to increment a variable that doesn't exist the first time. Full source code is [here].

Example from this week's Python course.