What is a function parameter =[] for?
Marko Rauhamaa
marko at pacujo.net
Fri Nov 20 07:28:17 EST 2015
BartC <bc at freeuk.com>:
> On 20/11/2015 01:05, Steven D'Aprano wrote:
>> On Fri, 20 Nov 2015 04:30 am, BartC wrote:
>>> The whole concept of 'mutable' default is alien to me. A default is just
>>> a convenient device to avoid having to write:
>>>
>>> fn(0) or fn("") or fn([])
>>
>> Says who?
>
> People who want to avoid having to write:
>
> fn(0) or fn("") or fn([])
Undoubtedly a mutable default value can lead to accidents. However, I
already showed C++ default values can also be mutable and lead to
analogous problems, so the question is not related to Python alone.
If there is a risk of a default [] or {} ending up in the wrong hands,
you can always write your function with a sentinel:
omitted = object()
def f(collection=omitted):
if collection is omitted:
collection = []
...
> We're arguing at cross-purposes then since you are obviously
> interested in these esoteric aspects,
The Ackermann function really is an esoteric example, but the other
example that has been discussed here can make practical use of the
default-value semantics:
[ lambda x: i * x for i in range(4) ]
which is salvaged with a default value:
[ lambda x, i=i: i * x for i in range(4) ]
or, more hygienically:
[ (lambda i=i: lambda x: i * x)() for i in range(4) ]
Even more appropriately, you may expressly want a mutable, singleton
object to be the default:
def initiate_query(query, database=global_database):
> but all I want to do is avoid remembering a long list of defaults.
> Here's an example from another language, a function I'm working on at
> the minute:
>
> function asklist(caption,&data,n=1, rows=10, width=50, flags="",
> buttons=(), tablist=(), heading="")=
One could argue that you should always use a sentinel object for default
values. That also allows you to distinguish between omitted values and
default values:
def asklist(caption, data, n=omitted, rows=omitted, width=omitted,
flags=omitted, buttons=omitted, tablist=omitted,
heading=omitted):
but that would be rather pedantic in most circumstances.
Marko
More information about the Python-list
mailing list