C-style static variables in Python?
Paul McGuire
ptmcg at austin.rr.com
Fri Apr 2 13:28:13 EDT 2010
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_
@self_aware
def foo():
this.counter += 1
print this.counter
foo.counter = 0
foo()
foo()
foo()
Prints:
1
2
3
-- Paul
More information about the Python-list
mailing list