using "private" parameters as static storage?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Nov 13 23:04:01 EST 2008


On Thu, 13 Nov 2008 14:25:08 -0800, Paul Boddie wrote:

> 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...

For some definition of "clean".

http://archive.eiffel.com/doc/manuals/technology/bmarticles/joop/
globals.html

http://weblogs.asp.net/wallen/archive/2003/05/08/6750.aspx

Python globals aren't quite as bad, because they are merely global to a 
module and not global to your entire application. Nevertheless, your 
example is one of the *worst* usages for globals. See below.


> 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.

Nonsense. Any other function in the code can write to spam_count and 
cause all sorts of havoc. Any function that needs to temporarily modify 
spam_count needs to be careful to wrap it with a save and a restore:

n = spam_count
spam_count = 47
s = spam()
spam_count = n


This is precisely one of the anti-patterns that global variables 
encourage, and one of the reasons why globals are rightly considered 
harmful. Don't Do This.



-- 
Steven



More information about the Python-list mailing list