static variables in Python?

Colin J. Williams cjw at ncf.ca
Wed Jul 30 00:29:23 CEST 2008


kj wrote:
> In <w8CdnQGPtuvdGRLVnZ2dnUVZ_r7inZ2d at comcast.com> Larry Bates <larry.bates at websafe.com`> writes:
> 
>> kj wrote:
>>> Yet another noob question...
>>>
>>> Is there a way to mimic C's static variables in Python?  Or something
>>> like it?  The idea is to equip a given function with a set of
>>> constants that belong only to it, so as not to clutter the global
>>> namespace with variables that are not needed elsewhere.
>>>
>>> For example, in Perl one can define a function foo like this 
>>>
>>> *foo = do {
>>>   my $x = expensive_call();
>>>   sub {
>>>     return do_stuff_with( $x, @_ );
>>>   }
>>> };
>>>
>>> In this case, foo is defined by assigning to it a closure that has
>>> an associated variable, $x, in its scope.
>>>
>>> Is there an equivalent in Python?
>>>
>>> Thanks!
>>>
>>> kynn
> 
> 
>> First names in Python are just that, names that point to objects.  Those objects 
>> can contain any type of information including other objects.  They are NOT 
>> buckets where things are stored.
> 
>> 1) Names (variables in Perl/C) defined within a Python function are placed in 
>> its local namespace.  They are not visible in the global namespace.
> 
>> 2) Yes you can have a local name point to a global.  This is often used in 
>> classes with attributes because looking up local is somewhat quicker than 
>> looking up the class attribute.
> 
>> def foo():
>>   x = expensive_call
>>   return do_stuff_with(x())
> 
> Maybe I'm missing your point, the goal is to have a "runtime
> constant" associated with the function.  In the your definition of
> foo, expensive_call gets called every time that foo gets called;
> this is what I'm trying to avoid!
> 
> Maybe it's easier to see what I mean with JavaScript:
> 
> function foo() {
>   if (foo.x === undefined) foo.x = expensive_call();
>   return do_stuff_with(foo.x);
> }
> 
> Here, expensive_call is called only once (assuming it never returns
> undefined).
> 
> OK, I guess that in Python the only way to do what I want to do is
> with objects...
> 
> kynn

You might consider using a singleton class.

Colin W.



More information about the Python-list mailing list