[Python-ideas] proto-PEP: Fixing Non-constant Default Arguments

Roman Susi rnd at onego.ru
Tue Jan 30 21:03:25 CET 2007


Chris Rebert wrote:
> Jim Jewett wrote:
> 
>>On 1/28/07, Chris Rebert <cvrebert at gmail.com> wrote:

/skip/

>>
>>>     def foo(bar=new baz):
>>>         #code
>>
>>This would be less bad.
>>
>>That said, I fear many new programmers would fail to understand when
>>they needed new and when they didn't, so that in practice, it would be
>>just optional random noise.
> 
> 
> This is part of the reason I'm trying to avoid adding new syntax. 
> However, I assert that at least 'new' is clearer than the' x=None; if x 

But if you are concerned with the current None, there could be some
other, new False value serving the same need, like:

    def foo(x, y, z, bar=Missing, qux=Missing):
        if baz is Missing:
            baz = []
        #code

or even:

    def foo(x, y, z, bar=, qux=):
        if baz is Missing:
            baz = []
        #code

at least, it doesn't require decorators, is backward compatible
(hopefully no grammar conflicts in there), reads as English.



> is None: x=expr' idiom in that it expresses one's intent more clearly. 
> Also, this would at least be a prettier way to spell the idiom even if 
> the reason still needed explaining. Alternatively, we could make the new 
> semantics the default and have syntax to use the old semantics via 
> 'once' or some other keyword. This does nicely emphasize that such 
> semantics would be purely for optimization reasons. I think I'll add 
> this to the PEP.
> 
> 
>>>Demonstrative examples of new semantics:
>>>     #default argument expressions can refer to
>>>     #variables in the enclosing scope...
>>>     CONST = "hi"
>>>     def foo(a=CONST):
>>>         print a
>>
>>This would work if there were any easy way to create a new scope.  In
>>Lisp, it makes sense.  In python, it would probably be better to just
>>find a way for functions to refer to their own decorations reliably.
> 
> 
> This is outside of the scope of my PEP. However, the below improvement 
> should help and you could always use one of the other refactorings to 
> work around this issue.
> 
> 
>>>Backwards Compatibility
>>>
>>>     This change in semantics breaks all code which uses mutable default
>>>argument values. Such code can be refactored from:
>>>
>>>     def foo(bar=mutable):
>>>         #code
>>>
>>>to
>>
>>   [a decorator option uses 3 levels of nested functions, which aren't even
>>   generic enough for reuse, unless you give up introspection.]
>>
>>No.  It could be done with a (more complex) decorator, if that
>>decorator came with the stdlib (probably in functools)
> 
> 
> Agreed, the decorator could be better. I've just enhanced it using 
> functools.wraps, which should help with the introspection issues you 
> raise. Other improvements to the refactoring code in the PEP are welcomed.
> 
> - Chris Rebert



More information about the Python-ideas mailing list