New submission from Serhiy Storchaka <[email protected]>:
This is yet one alternative to PEP 570. It does not solve all problems that PEP
570 is purposed to solve, but it significantly reduces the need in
positional-only parameters.
Currently the problem with implementing in Python functions that should accept
arbitrary keyword arguments is that argument names can conflict with names of
other parameters (in particularly "self"). For example, look at the function
def log(fmt, **kwargs):
print(fmt.format_map(kwargs))
You cannot call log('Format: {fmt}', fmt='binary'), because the argument for
parameter "fmt" is specified twice: as positional argument and as keyword
argument.
The idea is that if the function has the var-keyword parameter, then keyword
arguments with names which match passed positional arguments will be saved into
the var-keyword dict instead of be error.
The advantage of this idea over alternatives is that it does not need changing
the user code. Implementing this feature will fix the user code that we do not
even see. Most functions that otherwise would need positional only parameters
(over 60 in the stdlib) will be automatically fixed by this feature. We could
revert the deprecations added in issue36492 and simplify few functions that
used the *args hack before.
The change itself is very simple, just modification of few lines in ceval.c and
inspect.py.
The disadvantage is that it does not help with optional parameters. For example:
def make_dict(dict=(), **kwargs):
res = {}
res.update(dict)
res.update(kwargs)
return res
make_dict(dict={}, list=[]) will still return {'list': []} instead of {'dict':
{}, list: []}. You still need to use the *args hack to get the latter result.
But there are not much such functions.
This idea was proposed by Steve [1].
[1]
https://discuss.python.org/t/pep-570-python-positional-only-parameters/1078/39
----------
components: Interpreter Core
messages: 339392
nosy: gvanrossum, serhiy.storchaka, steve.dower
priority: normal
severity: normal
status: open
title: Avoid conflicts when pass arbitrary keyword arguments to Python function
type: enhancement
versions: Python 3.8
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue36518>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com