[Python-ideas] Idea: Deferred Default Arguments?

Kyle Lahnakoski klahnakoski at mozilla.com
Tue Jul 24 08:26:09 EDT 2018


I agree this is a problem, which I have seen solved by removing the
method signature, which is unfortunate:

> def flexible_method(**kwargs):
>     # Read the code to find out the expected parameters   

I have an @override decorator to handle this type of pattern. It will
perform the null-coalescing with properties found in a special "kwargs"
parameter. "kwargs" is assigned a dict that has a copy of the method
arguments. The value of a callee's argument is, in order,

* a not None value provided by the caller or
* a not None value found in the kwargs dict or
* the default value provided by the method declaration or
* None

I was not clear on where you wanted to define your defaults.  Either
like this:

>     @override
>     def subfunction_1(a=None, b=None, c=None, kwargs=None):
>         return a+b*c
>
>     @override
>     def subfunction_2(d=None, e=None, f=None, kwargs=None):
>         return d*e+f
>
>     @orverride
>     def main_function(a=2, b=3, c=4, d=5, e=6, f=7, kwargs=None):
>         return subfunction_1(a, b, c) + subfunction_2(d, e, f)
>         return subfunction_1(kwargs) + subfunction_2(kwargs)  # IF YOU
WANT TO BE LAZY

or like this:

>     @override
>     def subfunction_1(a=2, b=3, c=4, kwargs=None):
>         return a+b*c
>
>     @override
>     def subfunction_2(d=5, e=6, f=7, kwargs=None):
>         return d*e+f
>
>     @orverride
>     def main_function(a=None, b=None, c=None, d=None, e=None, f=None,
kwargs=None):
>         return subfunction_1(a, b, c) + subfunction_2(d, e, f)
>         return subfunction_1(kwargs) + subfunction_2(kwargs)  # IF YOU
WANT TO BE LAZY

both are identical except for where you declare the default values.


https://github.com/klahnakoski/mo-kwargs



More information about the Python-ideas mailing list