static variables in Python?

castironpi castironpi at gmail.com
Tue Jul 29 23:28:48 EDT 2008


On Jul 29, 8:38 pm, pigmartian <scottp... at comcast.net> wrote:
> bearophileH... at lycos.com wrote:
> > kj:
> >> OK, I guess that in Python the only way to do what I want to do
> >> is with objects...
>
> > There are other ways, like assigning the value out of the function,
> > because Python functions too are objects:
>
> ...
> > But I suggest you to use a class in this situation, it's often the way
> > that will keep your code more bug-free, and more readable by near-
> > casual readers too. Python philosophy asks you to write readable code
> > instead of clever code when possible, this is a difference from Perl,
> > I presume.
>
> > Bye,
> > bearophile
>
> Here's a solution using decorators, I like it, but I'm biased:
>
> def staticAttrs(**kwds):
>         """
>         Adds attributes to a function, akin to c-style
>         "static" variables
>         """
>
>         def _decorator(fcn):
>                 for k in kwds:
>                         setattr(fcn, k, kwds[k])
>                 return fcn
>         return _decorator
>
> @staticAttrs(n=0)
> def rememberCalls():
>         """
>         >>> rememberCalls()
>         0
>         >>> rememberCalls()
>         1
>         >>> rememberCalls()
>         2
>         """
>         print rememberCalls.n
>         rememberCalls.n += 1
>
> ~Scott

I like it too.  It also thought of (implementation not shown):

@has_locals
def rememberCalls( self ):
  self.val= 0
  self.ref= object( )

where self is preserved between calls and is an instance of a custom
class, possibly empty.  If you want more than one, but still
preserved:

rememberCallsA= has_locals( rememberCalls )
rememberCallsB= has_locals( rememberCalls )

You might want to make self a small and lightweight dict-only object:

@has_locals
def rememberCalls( dic ):
  dic['val']= 0
  dic['ref']= object( )



More information about the Python-list mailing list