Static Variables
Andrew Dalke
dalke at dalkescientific.com
Tue Apr 2 23:05:45 EST 2002
Jim Jacobs:
>Is it possible to simulate "C" style static variables in functions? In
>methods?
Depends on which aspect you're looking for. You probably want
something like:
_cache = {}
def spam(i):
if i in _cache:
return _cache[i]
x = hairy_algorithm_with_big_pointy_teeth(i)
_cache[i] = x
return x
Notes on the differences:
'_cache = {}' is executed once, but during module import. In C,
all statics are initialized before main is called (or is that C++?).
'static' is used in C functions as a way to hide scope. That's
less needed in Python because module variable have module scope, while
C variables have "compilation unit" scope.
If you wanted to change the actual value of '_cache' (that is,
replace it with a different reference) you would need to declare it
in the function as 'global'.
Variables starting with an '_' are not imported during "import *"
If you want more complicated functions, you can also create a
function object, like
class spam:
def __init__(self):
self._cache = {}
# prefill the cache
for i in range(10):
self(i)
def __call__(self, i):
if i in self._cache:
return _cache[i]
x = hairy_algorithm_with_big_pointy_teeth(i)
_cache[i] = x
return x
spam = spam()
'static' does other things than this; is there something else you
are looking for?
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list