using "private" parameters as static storage?

Paul Boddie paul at boddie.org.uk
Thu Nov 13 17:25:08 EST 2008


On 13 Nov, 18:16, Joe Strout <j... at strout.net> wrote:
> One thing I miss as I move from REALbasic to Python is the ability to
> have static storage within a method -- i.e. storage that is persistent
> between calls, but not visible outside the method.  I frequently use
> this for such things as caching, or for keeping track of how many
> objects a factory function has created, and so on.

Why not use a module global? It isn't hidden, but it is quite a clean
approach. Modifying your example...

spam_count = 0

def spam():
    global spam_count
    spam_count += 1
    return "spam " * spam_count

[...]

> This doesn't expose any uncleanliness outside the function at all.

I wouldn't be too worried about that. Although namespaces can become
somewhat crowded with all these extra names, there can be benefits in
exposing such names, too, but if you find this too annoying, it could
be advisable to collect these entries and put them in another
namespace, maybe a class or a module.

Paul



More information about the Python-list mailing list