Persistent variables in python
Lee Harr
missive at frontiernet.net
Tue Dec 26 18:11:02 EST 2006
> Found out a quite fun way to store persistent variables in functions in
> python.
>
> Is this concidered bad coding practice since I guess persistent
> variables in functions are not meant to be?
I am using is in one of my recent projects. I was thinking of
it sort of like "static" variables in C.
I use a decorator to create the variables ...
def static(**kw):
'''
Used to create a decorator function that will add an
attribute to a function and initialize it.
>>> @static(foo=5)
... def bar():
... print bar.foo
... bar.foo += 1
...
>>> bar()
5
>>> bar()
6
'''
def decorator(f):
f.__dict__.update(kw)
return f
return decorator
More information about the Python-list
mailing list