[Python-ideas] Idea: Deferred Default Arguments?

Peter O'Connor peter.ed.oconnor at gmail.com
Fri Jul 20 05:03:12 EDT 2018


Often when programming I run into a situation where it would be nice to
have "deferred defaults".  Here is an example of what I mean:

    def subfunction_1(a=2, b=3, c=4):
        return a+b*c

    def subfunction_2(d=5, e=6, f=7):
        return d*e+f

    def main_function(a=2, b=3, c=4, d=5, e=6, f=7):
        return subfunction_1(a=a, b=b, c=c) + subfunction_2(d=d, e=e, f=f)

Here you can see that I had to redefine the defaults in the main_function.
In larger codebases, I find bugs often arise because defaults are defined
in multiple places, and somebody changes them in a lower-level function but
fails to realize that they are still defined differently in a higher
function.

The only way I currently see to achieve this is not very nice at all, and
completely obfuscates the signature of the function:

    def main_function(**kwargs):
        return subfunction_1(**{k: v for k, v in kwargs.items() if k in
['a', 'b', 'c']})
               + subfunction_2(**{k: v for k, v in kwargs.items() if k in
['d', 'e', 'f']})

What I was thinking was a "deferred" builtin that would just allow a lower
function to define the value (and raise an exception if anyone tried to use
it before it was defined)

    def main_function(a=deferred, b=deferred, c=deferred, d=deferred,
e=deferred, f=deferred):
        return subfunction_1(a=a, b=b, c=c) + subfunction_2(d=d, e=e, f=f)

I assume this has been discussed before somewhere, but couldn't find
anything on it, so please feel free to point me towards any previous
discussion on the topic.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180720/2e168bc2/attachment.html>


More information about the Python-ideas mailing list