Mutable default values for function parameters

Terry Reedy tjreedy at home.com
Thu Oct 4 09:34:50 EDT 2001


"sebastien" <s.keim at laposte.net> wrote in message
news:7da8d8f8.0110040056.42443bb at posting.google.com...
> 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
static.
For above, insert 'variant(None)' before while loop to reinitialize
old_data.

> I've seen the same problem in
> http://www-106.ibm.com/developerworks/library/l-pycon.html?n-l-9271
>
>    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
randomwalk_static():
def randomwalk_static(restart=0, last = [1]):
  if restart:
     last = [1]
     return
...
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