C-style static variables in Python?

Albert van der Horst albert at spenarnc.xs4all.nl
Thu Apr 15 10:38:22 EDT 2010


In article <mailman.1441.1270165718.23598.python-list at python.org>,
Steve Holden  <steve at holdenweb.com> wrote:
>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.

Imagine that heavy_lifting is only ever used here and uses 4 Gbyte of core.
Suddenly deleting those function objects seems the right thing to do,
instead of an obscure technique.
(I'm not sure the Python compiler could take advantage of this,
I know I could in my Forth compiler, under circumstances.)

>
>regards
> Steve
>--
>Steve Holden           +1 571 484 6266   +1 800 494 3119

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst




More information about the Python-list mailing list