C-style static variables in Python?

Steve Holden steve at holdenweb.com
Thu Apr 1 19:10:57 EDT 2010


Chris Rebert wrote:
> 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.

But the real problem is that the OP is insisting on using purely
procedural Python when the problem is screaming for an object-oriented
answer.

If the function were instead a method then the instance namespace would
be the logical place to store the required data.

regards
 Steve
regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/




More information about the Python-list mailing list