It is common to see keyword arguments passed values from identifiers (typically local variables) with the same name as the argument. Here’s an example from the pytorch library:
func(params,
d_p_list,
momentum_buffer_list,
weight_decay=weight_decay,
momentum=momentum,
lr=lr,
dampening=dampening,
nesterov=nesterov,
has_sparse_grad=has_sparse_grad,
maximize=maximize)
My proposal is to allow these keyword arguments to be passed as e.g. weight_decay
instead of weight_decay=weight_decay
This would apply only where positional arguments are not allowed e.g. arguments which are forced to be keyword-only in the function definition or arguments following at least one explicit keyword argument at the call site
I would also propose allowing *
at the call site to force keyword arguments, analogous to the use of *
to force keyword only arguments in the function definition, added by PEP 3102
The principal benefit would be to eliminate redundant typing in function calls like the example above, which now becomes:
func(params,
d_p_list,
momentum_buffer_list,
# following arguments are all keyword, due to * in the function definition after momentum_buffer_list
weight_decay,
momentum,
lr,
dampening,
nesterov,
has_sparse_grad,
maximize)
A particular application would be the case of packing variables into a dictionary, where we could then abbreviate:
dict(a=a, b=b, c=c)
as:
dict(*, a, b, c)
Note that this proposal does not change the behaviour of any existing valid python code. It only gives a valid meaning to some previously invalid syntax, therefore no ordinary existing code should be impacted
There could be extraordinary cases which are impacted e.g. automatic code generation which speculatively tries to generate possibly invalid code and tests it empirically with eval
/exec
/compile
I feel that this change naturally extends PEP 3102 and with hindsight could have been included as part of that PEP
It also relates indirectly to the support for =
in format strings, added in Python 3.8. The similarity being that in both cases we are allowing that the form of an expression in code, not just the value of the expression at runtime, can be impactful. This is aspect is fairly rare, so I thought it’s worth pointing out that this isn’t unprecedented in Python
I realise there is a very high bar for this kind of language change! In any case I am interested to hear the views of others, especially any problematic situations for this proposal which I haven’t thought of