Newbie: anything resembling static?

Tom nonotreally999 at yahoo.com
Sat Feb 1 16:05:09 EST 2003


Alex Martelli <aleax at aleax.it> wrote in message news:<96YZ9.102138$0v.2963371 at news1.tin.it>...
> anton wilson wrote:
> 
> > Is there any way of imitating "static" C function variables without having
> > to define the variable as a global? I just want persistent function
> > variables but i want them to be local to the function namespace. :S

<alex>

> 
> There are several ways you can approximate this effect, e.g.:
> 

<snip> 

> def five():
>     staticvar = []
>     def innerfive():
>         staticvar.append('x')
>         return ''.join(staticvar)
>     return innerfive
> five = five()

I've played around with the several options in Alex's msg and learned
some things I didn't know about nested scopes.  (Thanks, Alex.)  I
also read PEP 227 (and understood many parts of it), but I still have
one question: after I've called the function 'five' several times, is
there a way to see the current value of 'staticvar' in an interactive
session?

Something like:
------------------------------
>>> five()
'x'
>>> five()
'xx'
>>> five()
'xxx'
>>>
>>> five.innerfive.staticvar
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: 'function' object has no attribute 'innerfive'
>>> 
------------------------------

I understand why 'five.innerfive.staticvar' doesn't work.  What will? 
Don't have any use case in mind, just curious.

TIA,
Tom




More information about the Python-list mailing list