C-style static variables in Python?

Chris Rebert clp2 at rebertia.com
Thu Apr 1 18:51:16 EDT 2010


On Thu, Apr 1, 2010 at 3:34 PM, kj <no.email at please.post> wrote:
> When coding C I have often found static local variables useful for
> doing once-only run-time initializations.
<snip>
> Another approach would be to stuff the static values in the function's
> __dict__.  This is less satisfactory than the closure approach
> because the "pseudo-static" variable is accessible from outside
> the function, but the code is arguably a little more straightforward,
> and one does not end up with the now useless one-time closure-generating
> function kicking around.  Here's another version of the function
> above:
>
>>>> def spam():
> ...     d = spam.__dict__
> ...     if not 's' in spam.__dict__:
> ...         spam.s = 1
> ...     print spam.s
> ...     spam.s += 1
> ...
>>>> spam()
> 1
>>>> spam()
> 2
>>>> spam()
> 3
>
> Besides the external accessibility issue, I don't like explictly
> coding the name of the function within the function.  Is there any
> way to have the function access its own __dict__ without having to
> explicitly code its name in its body?  E.g., is there some generic
> special variable that, within a function, refers to the function
> object itself?

Nope. It's been proposed in that past
(http://www.python.org/dev/peps/pep-3130/), but that proposal was
rejected.

> I'm sure that there are many other ways to skin this cat, especially
> if one starts definining fancy callable classes and whatnot.  But
> is there a better *simple* way to achieve C-style static locals in
> Python that does not require a lot of extra machinery?

You can abuse the default argument value mechanism:

def spam(s_cell=[1]):
    s = s_cell[0]
    print s
    s_cell[0] += 1

It's a bit less ugly when the value itself is mutable, which isn't the
case here with the integer.

Personally, I hate such abuse with a passion; I think a global
variable is clearest.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list