[IronPython] [python] Static variables (Python basics)

Michael Foord fuzzyman at voidspace.org.uk
Sun Sep 30 16:51:28 CEST 2007


David Seruyange wrote:
> Hey everyone,
>
> I'm wondering how one caches things in python in a manner similar to 
> how a static variable or class member might in C#.  I can only think 
> of an equivalent in something like a global variable, but is there 
> another? I'm not good enough yet to think in a manner "pythonic" but 
> I've an inkling that a generator may do this?  This program (where I 
> want to cache a list of factorials once computed) is what prompted my 
> questions:

Well, if you're using a class then you can also use class members. For 
functions then using a global variable as a cache is fairly normal.

There are various other approaches though - for example see the memoize 
decorator that caches function call results:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496879

This one uses an inner function and has the cache in the outer scope - 
so that each memoized function has its own cache.

Michael
http://www.manning.com/foord

>
> f = [1]   
>    
> def fact(n):
>     if n == 1:return 1
>     if(n > len(f)):
>         for i in range(len(f), n+1):
>             f.append(i * f[i -1])
>     return f[n]
>            
> print fact(4) #set it up
> print fact(3) #pulled from cache
> print fact(6) #grow it
>
>
> ------------------------------------------------------------------------
> Boardwalk for $500? In 2007? Ha!
> Play Monopoly Here and Now 
> <http://us.rd.yahoo.com/evt=48223/*http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow> 
> (it's updated for today's economy) at Yahoo! Games.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Users mailing list
> Users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
>   




More information about the Ironpython-users mailing list