On Mon, Nov 15, 2021 at 4:18 AM Peter O'Connor
<[email protected]> wrote:
>
> On Mon, Mar 22, 2021 at 1:28 PM Caleb Donovick <[email protected]>
> wrote:
>>
>> ... One could do something like:
>> ```
>> def fun(a, b=0): ...
>> def wraps_fun(args, b=inspect.signature(fun).parameters['b'].default): ...
>> ```
>> But I would hardly call that clear.
>>
>> Caleb
>
>
>
> I like this approach too - it just needs a cleaner syntax. Python could make
> functions more "object like" by having fields for args (though I'm sure that
> would inspire some controversy):
>
> def fun(a, b=0): ...
> def wraps_fun(args, b=fun.args.b.default): ...
>
Functions ARE objects, so they can't really be more "object-like" :)
But they have their argument defaults in a slightly different way:
func.__defaults__ is a tuple of default values for the rightmost N
arguments, and func.__kwdefaults__ is a mapping from name to default
for keyword-only arguments. If you want to be able to look up any
argument (positional-only, pos-or-kwd, keyword-only) by name, you need
something that digs through the function's details and gives back that
mapping - and that's what inspect.signature does.
So yes, it's not exactly clear... but it's also not really something
you should be doing a lot of. Also, it's entirely possible that future
versions of Python will have a concept of optional arguments that
don't *have* defaults, so the entire idea of passing the default
wouldn't work.
Currently, the only way to truly say "maybe pass this argument", is to
use *args or **kwargs.
spam(*(1,) * use_eggs)
spam(**{"eggs": 1} if use_eggs else {})
Still clunky, but legal, and guaranteed to work in all Python
versions. It's not something I've needed often enough to want
dedicated syntax for, though.
ChrisA
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/FMXRNUWN5ROCIACJN74ANP3UDJM3SGEL/
Code of Conduct: http://python.org/psf/codeofconduct/