modifying static (local) method variables

Steven Bethard steven.bethard at gmail.com
Fri Nov 12 11:57:45 EST 2004


t scytale <scytale <at> gmail.com> writes:
> 
> i am using a mutable default paramater to simulate a static method variable.
> i notice that 
> - assigning to the var inside the method causes it to return to the
> default value at each call.
> - appending to the var gives the expected behaviour (the value is
> preserved to the next call

This is true of any parameter value:

>>> def f(x):
... 	x = []
... 	x.append(1)
... 	return x
... 
>>> lst = []
>>> lst2 = f(lst)
>>> lst is lst2
False
>>> lst, lst2
([], [1])
>>> def f(x):
... 	x.append(1)
... 	return x
... 
>>> lst = []
>>> lst2 = f(lst)
>>> lst is lst2
True
>>> lst, lst2
([1], [1])

Note that in Python, the parameters to your method are just names that will be
bound to particular objects.  When you "assign" to a parameter within a
function, what you're really doing is rebinding the name.  This means that the
name is now bound to whatever new object you give it.  In my example above, you
can see that the first f function rebinds x to a new empty list.  When I modify
the new empty list, I am modifying the object currently bound to the name 'x'
(the new empty list), not the object passed in to the function.  Note that when
I do not rebind x, I can modify the object that was passed in as I like.

Using default parameter values does not change this.  All default parameter
values do for you is to bind a given parameter name to a given default value if
no value for that parameter is passed to the function.  If you rebind the name
within the function, you will again lose access to the previous value bound to
that name.

HTH,

Steve




More information about the Python-list mailing list