using "private" parameters as static storage?

Joe Strout joe at
Fri Nov 14 19:08:44 CET 2008

On Nov 13, 2008, at 8:26 PM, Steven D'Aprano wrote:

>> def spam(_count=[0]):
>>      _count[0] += 1
>>      return "spam " * _count[0]
> This is a common trick, often used for things like caching. One major
> advantage is that you are exposing the cache as an *optional* part  
> of the
> interface, which makes testing easier. For example, instead of a test
> that looks something like this:
> cache = get_access_to_secret_cache()  # somehow
> modify(cache)
> result = function(arg)
> restore(cache)
> assert something_about(result)
> you can simple do this:
> result = function(arg, _cache=mycache)
> assert something_about(result)

That's a very good point.  I'd been working under the assumption that  
any outside mucking with the cache was a Bad Thing, but for testing,  
it can be darned helpful.  And this is a very safe form of mucking; it  
doesn't actually affect the "real" cache at all, but just substitutes  
a temporary one.

Thanks also for pointing out that this is a common trick -- after all  
the attacks on the very idea last night, I was wondering if I were off  
alone in the woods again.

>> def spam2():
>>      if not hasattr(spam2,'count'):spam2.count=0 spam2.count += 1
>>      return "spam2 " * spam2.count
>> This doesn't expose any uncleanliness outside the function at all.  
>> The
>> drawback is that the name of the function has to appear several times
>> within itself, so if I rename the function, I have to remember to  
>> change
>> those references too.  But then, if I renamed a function, I'd have to
>> change all the callers anyway.  So maybe this is better. What do  
>> y'all
>> think?
> I've used this myself, but to me it feels more icky than the semi- 
> private
> argument trick above.

Thanks for the feedback.

- Joe

More information about the Python-list mailing list