C-style static variables in Python?

Terry Reedy tjreedy at udel.edu
Fri Apr 2 21:48:22 EDT 2010


On 4/2/2010 1:28 PM, Paul McGuire wrote:
> On Apr 1, 5:34 pm, kj<no.em... at please.post>  wrote:
>> When coding C I have often found static local variables useful for
>> doing once-only run-time initializations.  For example:
>>
>
> Here is a decorator to make a function self-aware, giving it a "this"
> variable that points to itself, which you could then initialize from
> outside with static flags or values:
>
> from functools import wraps
>
> def self_aware(fn):
>      @wraps(fn)
>      def fn_(*args):
>          return fn(*args)
>      fn_.__globals__["this"] = fn_
>      return fn_

In 3.1, at least, the wrapper is not needed.

def self_aware(fn):
     fn.__globals__["this"] = fn
     return fn

Acts the same

> @self_aware
> def foo():
>      this.counter += 1
>      print this.counter
>
> foo.counter = 0

Explicit and separate initialization is a pain. This should be in a 
closure or class.

> foo()
> foo()
> foo()
> Prints:

> 1
> 2
> 3

However, either way, the __globals__ attribute *is* the globals dict, 
not a copy, so one has

 >>> this
<function foo at 0x00F5F5D0>

Wrapping a second function would overwrite the global binding.

Terry Jan Reedy




More information about the Python-list mailing list