Default mutable parameters in functions

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Apr 4 10:34:21 EDT 2014


On Fri, 04 Apr 2014 10:00:25 -0400, random832 wrote:

> On Thu, Apr 3, 2014, at 20:38, Mark Lawrence wrote:
>> I just wish I had a quid for every time somebody expects something out
>> of Python, that way I'd have retired years ago.  At least here it's not
>> accompanied by "as that's how it works in <some other language>".
> 
> I can't imagine a language that would work that way. 

That seems like a failure of imagination to me. At least, I can't imagine 
anyone unable to imagine a language like that :-P


> For one, it would
> also imply that passing a value would change the default for future
> calls even for non-mutable types.

Not all programming languages distinguish between mutable and non-mutable 
types. Or for that matter even have types.

But it's not hard to get that effect in Python, mutable or immutable 
doesn't matter:


py> def spam(count, food="spam"):
...     spam.__defaults__ = (food,)
...     return food*count
...
py> spam(5)
'spamspamspamspamspam'
py> spam(3, 'eggs')
'eggseggseggs'
py> spam(5)
'eggseggseggseggseggs'
py> spam(5, 3)
15
py> spam(4)
12


Is it so unusual for a function to want to store persistent state which 
survives from one call to another but may also vary from time to time? 
Managing situations like that is one of the reasons OOP was invented!




-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list