[英]Unpack multiple dictionaries as functional arguments without repeating double asterisk
I use API with long name of argument parameters.我使用参数参数长名称的 API。 Consequently, I create following dictionaries for most common combinations of values which are then unpacked in function calls.因此,我为最常见的值组合创建了以下字典,然后在函数调用中解包。
a_T = {'API parameter a': True}
a_F = {'API parameter a': False}
b_100 = {'API parameter b': 100}
b_0 = {'API parameter b': 0}
hello = {'API parameter c': 'hello'}
bye = {'API parameter d': 'goodbye'}
myf(**a_T, **bye)
myf(**b_0)
myf(**a_F, **b_100, **hello, **bye)
Is there any way to avoid repeat double asterisk?有什么办法可以避免重复双星号? The code becomes quite unreadable with many of these strange characters.许多这些奇怪的字符使代码变得非常难以阅读。
Once could then add this unpacking utility to myf:然后可以将这个解包实用程序添加到 myf:
myf(a_T, bye)
myf(b_0)
myf(a_F, b_100, hello, bye)
You can actually use |
您实际上可以使用|
for Python 3.9+ to combine all the dictionaries then send unpacked version.用于 Python 3.9+ 组合所有字典,然后发送解压版本。
def fun(**kwargs):
print(kwargs)
>>> fun(**a_F| b_100| hello| bye)
{'API parameter a': False, 'API parameter b': 100, 'API parameter c': 'hello', 'API parameter d': 'goodbye'}
Or just use *args
and pass multiple dictionaries:或者只使用*args
并传递多个字典:
def fun(*args):
print(args)
>>> fun(a_F,b_100,hello,bye)
({'API parameter a': False}, {'API parameter b': 100}, {'API parameter c': 'hello'}, {'API parameter d': 'goodbye'})
Another solution is to use Python decorator and take care of ugly part inside the decorator function:另一种解决方案是使用 Python 装饰器并处理装饰器函数内部的丑陋部分:
def decorator(fun):
def wrapper(*args):
from functools import reduce
kwargs = reduce(lambda a, b: a | b, args)
return fun(**kwargs)
return wrapper
@decorator
def main_fun(**kwargs):
print(kwargs)
>>> main_fun(a_F,b_100,hello,z)
{'API parameter a': False, 'API parameter b': 100, 'API parameter c': 'hello', 'parameter 4': 'goodbye'}
To unpack a series of dicts, use dict.update
, or a nested comprehension:要解压一系列字典,请使用dict.update
或嵌套推导:
def myf(*dicts):
merged = {k: v for d in dicts for k, v in d.items()}
# do stuff to merged
OR或者
def myf(*dicts):
merged = {}
for d in dicts:
merged.update(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.