C-style static variables in Python?

Steve Holden steve at holdenweb.com
Fri Apr 2 01:48:18 CEST 2010


Terry Reedy wrote:
> On 4/1/2010 6:34 PM, kj wrote:
>>
>>
>> When coding C I have often found static local variables useful for
>> doing once-only run-time initializations.  For example:
>>
>> int foo(int x, int y, int z) {
>>
>>    static int first_time = TRUE;
>>    static Mongo *mongo;
>>    if (first_time) {
>>      mongo = heavy_lifting_at_runtime();
>>      first_time = FALSE;
>>    }
>>
>>    return frobnicate(mongo, x, y, z);
> 
> Global var or class or closure such as below (obviously untested ;=):
> 
> make_foo()
>   mongo = heavy_lifting_at_runtime();
>   def _(x,y,z):
>     return frobnicate(mongo, x, y, z)
>   return _
> foo = make_foo

I suspect you mean

foo = make_foo()

> del make_foo # to make sure it is *never* called again ;
> 
> Now you only have foo with a hard-to-access private object and no
> first_time checks when you call it.
> 
> Terry Jan Reedy
> 
I don't think I'd ever want to use such an obscure technique in a
program. You might want to consider using functools.wraps to make sure
that the foo function looks right.

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