C-style static variables in Python?
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):
> def fn_(*args):
> return fn(*args)
> fn_.__globals__["this"] = fn_
> return fn_
In 3.1, at least, the wrapper is not needed.
fn.__globals__["this"] = fn
Acts the same
> 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.
However, either way, the __globals__ attribute *is* the globals dict,
not a copy, so one has
<function foo at 0x00F5F5D0>
Wrapping a second function would overwrite the global binding.
Terry Jan Reedy
More information about the Python-list