47

There is a questions asking how to simulate static variables in python.

Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)

Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?

Edit:

I asked specifically about the why of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.

Community
  • 1
  • 1
Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
  • What was wrong with the answers to http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python? Why re-ask the question? – S.Lott Feb 27 '09 at 16:57
  • 6
    I explicitly didn't ask how to simulate it, but what the reason for this decision are. – Georg Schölly Feb 27 '09 at 19:22

9 Answers9

81

The idea behind this omission is that static variables are only useful in two situations: when you really should be using a class and when you really should be using a generator.

If you want to attach stateful information to a function, what you need is a class. A trivially simple class, perhaps, but a class nonetheless:

def foo(bar):
    static my_bar # doesn't work

    if not my_bar:
        my_bar = bar

    do_stuff(my_bar)

foo(bar)
foo()

# -- becomes ->

class Foo(object):
    def __init__(self, bar):
        self.bar = bar

    def __call__(self):
        do_stuff(self.bar)

foo = Foo(bar)
foo()
foo()

If you want your function's behavior to change each time it's called, what you need is a generator:

def foo(bar):
    static my_bar # doesn't work

    if not my_bar:
        my_bar = bar

    my_bar = my_bar * 3 % 5

    return my_bar

foo(bar)
foo()

# -- becomes ->

def foogen(bar):
    my_bar = bar

    while True:
        my_bar = my_bar * 3 % 5
        yield my_bar

foo = foogen(bar)
foo.next()
foo.next()

Of course, static variables are useful for quick-and-dirty scripts where you don't want to deal with the hassle of big structures for little tasks. But there, you don't really need anything more than global — it may seem a but kludgy, but that's okay for small, one-off scripts:

def foo():
    global bar
    do_stuff(bar)

foo()
foo()
Ben Blank
  • 54,908
  • 28
  • 127
  • 156
  • Ok for the fact that you indeed might be needing a class. Apart for the ugly Borg pattern, there is no real way to ensure this class is a singleton. Actually the importation of package makes it quite a pain. – fulmicoton Feb 27 '09 at 00:48
  • The class sample does not look like it is Python. I think you meant: "private bar" => "bar = None", and in init you'd have "self.my_bar = bar". – Heikki Toivonen Feb 27 '09 at 00:50
  • @Heikki Toivonen: Agreed, also in the first example "my_bar" doesn't have to be a class variable, an instance variable would work just as well. – dF. Feb 27 '09 at 02:29
  • @Paul: Use only class-level variables and @classmethod decorators and your class is also a singleton object. – S.Lott Feb 27 '09 at 02:57
  • +1 for concept, the python code needs to be cleaned as the above comments have said :) – Ryan Feb 27 '09 at 04:50
  • @all — Wow, I wasn't expecting this big a response. I admit the code hasn't been tested; I wrote this while away from a Python interpreter. I'll try to clean it up tomorrow. – Ben Blank Feb 27 '09 at 07:57
  • Thanks for the examples, though I didn't really need them as I've seen similar ones before. It was more about the decision not to have static variables. – Georg Schölly Feb 27 '09 at 09:23
  • @gs — I figured examples would be useful to future knowledge-seekers who find your question. – Ben Blank Feb 27 '09 at 17:16
  • @all — The code has been corrected and tested. Thanks for your gentle remonstrations. :-) – Ben Blank Feb 27 '09 at 17:27
19

One alternative to a class is a function attribute:

def foo(arg):
    if not hasattr(foo, 'cache'):
        foo.cache = get_data_dict()
    return foo.cache[arg]

While a class is probably cleaner, this technique can be useful and is nicer, in my opinion, then a global.

davidavr
  • 14,143
  • 4
  • 27
  • 31
  • 1
    What I don't like about it is the need write the method name over and over. If I changed the name I'd have to rewrite half the code. – Georg Schölly Feb 27 '09 at 09:25
  • 1
    @gs: Yes, this is a shortcoming. I was looking for some way to reference the current function instead of using the name (something like self) but I don't think there is such a way. You could do a "this = foo" at the very top and then reference "this" everywhere so a rename would be easy to maintain. – davidavr Feb 27 '09 at 12:37
  • This works as is, but you're really setting yourself up for trouble when someone passes foo around and receives NameError: global name 'foo' is not defined – Josh Lee Mar 08 '09 at 04:36
  • @jleedev: The globals used (which contain the name "foo") are the module globals from when the function is *created*, not where it's called from (that would imply dynamic scoping, rather than lexical). Passing it around won't make any difference. – Brian Apr 03 '09 at 12:58
8

In Python 3, I would use a closure:

def makefoo():
    x = 0
    def foo():
        nonlocal x
        x += 1
        return x
    return foo

foo = makefoo()

print(foo())
print(foo())
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
  • hello i am still trying to figure out how this works. Can u plz explain a little further? Thanks in advance. :) – BugShotGG Sep 26 '12 at 13:44
6

I think most uses of local static variables is to simulate generators, that is, having some function which performs some iteration of a process, returns the result, but mantains the state for the subsequent invocation. Python handles this very elegantly using the yield command, so it seems there is not so much need for static variables.

Il-Bhima
  • 10,744
  • 1
  • 47
  • 51
  • 1
    I'd like to use them to cache things loaded from disk. I think it clutters the instance less, if I could assign them to the function. – Georg Schölly Feb 26 '09 at 23:40
5

It's a design choice.

I'm assuming Guido thinks you don't need them very often, and you never really need them: you can always just use a global variable and tell everyone to keep their greasy paws offa' your variable ;-)

Jonas Kölker
  • 7,680
  • 3
  • 44
  • 51
  • uh, or you could pass objects around as normal. –  Feb 27 '09 at 17:41
  • 1
    suppose you want to use your own random generator in quicksort. Should callers pass in the randomness? No. Should it be updated between (otherwise independent) calls? Yes. Sometimes you don't want to pass around objects... – Jonas Kölker Mar 01 '09 at 02:49
4

For caching or memoization purposes, decorators can be used as an elegant and general solution.

Mr Fooz
  • 109,094
  • 6
  • 73
  • 101
0

The answer's pretty much the same as why nobody uses static methods (even though they exist). You have a module-level namespace that serves about the same purpose as a class would anyway.

Jason Baker
  • 192,085
  • 135
  • 376
  • 510
0

An ill-advised alternative:

You can also use the side-effects of the definition time evaluation of function defaults:

def func(initial=0, my_static=[])
  if not my_static:
    my_static.append(initial)

   my_static[0] += 1
  return my_static[0]

print func(0), func(0), func(0)

Its really ugly and easily subverted, but works. Using global would be cleaner than this, imo.

Richard Levasseur
  • 14,562
  • 6
  • 50
  • 63
-1

From one of your comments: "I'd like to use them to cache things loaded from disk. I think it clutters the instance less, if I could assign them to the function"

Use a caching class then, as a class or instance attribute to your other class. That way, you can use the full feature set of classes without cluttering other things. Also, you get a reusable tool.

This shows that on SO it always pays off to state one's problem instead of asking for a specific, low level solution (e.g. for a missing language feature). That way, instead of endless debates about simulating "static" (a deprecated feature from an ancient language, in my view) someone could have given a good answer to you problem sooner.

Ber
  • 40,356
  • 16
  • 72
  • 88