[Tutor] multiple class instances

Corran Webster cwebster@math.tamu.edu
Tue, 11 May 1999 10:35:39 -0500 (CDT)


On 10 May, Tim Peters wrote:
> [Corran Webster, explaining the unexplainable!]
>> I can't think of a situation where this sort of default argument
>> behaviour would be useful, although I'm sure Tim Peters could come up
>> with one <wink>.

[snip sort of example I thought might come up :) ]

> The other good use violates even that rule, but in this case the user is
> never supposed to supply a value:
> 
> def fac(n, _cache={}):
>     """fac(n) -> factorial of n; n must be >= 0."""
>     try:
>         return _cache[n]
>     except KeyError:
>         if n < 0:
>             raise ValueError("fac argument must be >= 0: " + `n`)
>         if n <= 1:
>             result = 1L
>         else:
>             result = n * fac(n - 1)
>         _cache[n] = result
>         return result

This is truly deviously evil.  Thank you.

> This is a common trick for speeding recursive functions, using _cache to
> remember the results that have already been computed.  You could do this
> with a global var _cache too, but this way hides the name and-- by making
> the name local instead of global --happens to slash the time it takes Python
> to "look the name up".  OTOH, if someone calls fac with *two* arguments, it
> will screw up the function beyond repair.

Hmmm... is it really going to be that much faster?  Presumably there is
some overhead associated with having to find the default value.

And of course someone could always clobber your _cache variable if you
use a more traditional approach.

> Fair summary:  Avoid mutable default values in functions and methods <wink>.

Corran