Mutable default values for function parameters

Terry Reedy tjreedy at
Thu Oct 4 15:34:50 CEST 2001

"sebastien" <s.keim at> wrote in message
news:7da8d8f8.0110040056.42443bb at
> For sample I have tried to do something like Eiffel loop variant:
> def variant(data, old_data=[None]):
> st = (data <> old_data[0])
> old_data[0] = data
> return st
> for i in range(5):
> assert variant(i)
> print i
> while i>0:
> assert variant(i)
> i -= 1
> This fail because old_data remain the same between the last loop in
> the for and the first one in the while.

Call function with value that will result in reinitialization of
For above, insert 'variant(None)' before while loop to reinitialize

> I've seen the same problem in
>    def randomwalk_static(last=[1]):    # init the "static" var(s)
> The first call of print_numl work fine, but later calls will fail
> because 'last' parameter will always contain a number <0.1
> Or maybe, someone could give me an obvious way to solve this kind of
> problems?

1. Add explicit reinitialization code to function.  For
def randomwalk_static(restart=0, last = [1]):
  if restart:
     last = [1]
randomwalk_static(1) #reinits and nothing else
This requires second argument, whether defaulted (as above) or not (as
in variant()) since assigning explicit value to mutable arg blocks
access to behind-the-scenes default value.
2. Make the static var global (ie, public instead of private) so you
can access it from outside the function to reinitialize.
3. Rewrite function of __call__ method of class that keeps static vars
as instance attributes.  This allows, in this case, multiple
randomwalks to be going at once.

No need to revise Python 8-).

Terry J. Reedy

More information about the Python-list mailing list