default argument value is mutable

Steve D'Aprano steve+python at pearwood.info
Fri Oct 7 09:27:29 EDT 2016


On Fri, 7 Oct 2016 11:48 pm, jmp wrote:

> On 10/07/2016 02:07 PM, ast wrote:

>> It can be used to store some variables from one call of
>> a function to an other one.
>>
>> def test( _store={'x':0}):
>>
>>     x = _store['x']
>>     ..... do some stuff
>>    _store['x'] = x
> 
> For personal dirty scripts, possibly, for all other situations, never.
> Especially since there's nothing in the code above that cannot be solved
> using standard idioms .


Using a default list as static storage *is* a standard idiom.



> That is if you care about anyone reading your code ;)

Here's another example of a mutable default argument:

https://www.python.org/doc/essays/graphs/

Although it isn't actually being mutated. Nevertheless, if it is good enough
for Guido, then it should be good enough for anyone.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list