[Python-ideas] Default arguments in Python - the return - running out of ideas but...

Steven D'Aprano steve at pearwood.info
Thu May 14 23:25:28 CEST 2009


On Thu, 14 May 2009 09:44:07 pm spir wrote:

> Generally speaking, I find ok the need of sentinels for clarifying
> rare and non-obvious cases such as runtime-changing default values:
>
> def somefunc(arg, m=UNDEF):
>     if m is UNDEF:
>         m = runtimeDefaultVal()
>
> While I do not find ok the need of a sentinel to avoid the common
> gotcha of a default value beeing "back-updated" when the
> corresponding local var is changed in the func body:
>
> def otherfunc(arg, l=UNDEF):
>     if l is UNDEF:
>         l = []
>     <possibly update l>

But those two idioms are the same thing!

In the first case, if m is not provided by the caller, your function has 
to produce a fresh object at runtime. It does this by calling 
runtimeDefaultVal() which returns some unspecified object.

In the second case, if l is not provided by the caller, your function 
has to produce a fresh object at runtime. It does this by calling []. 
This is merely a special case of the first case, where 
runtimeDefaultVal() simply returns [] every time.



-- 
Steven D'Aprano



More information about the Python-ideas mailing list