假设我们具有可变函数,例如以下内容:
def foo(*args, **kwargs):
pass
我想编辑foo,以便它打印争论列表。例如,我们需要以下代码...
foo(98, 99, 100, a = 1, b = 2, c = 3)
...打印...
98, 99, 100, a = 1, b = 2, c = 3
以下似乎可以解决问题:
import itertools
rep_kwarg = lambda kwarg: kwarg[0] + " = " + str(kwarg[1])
def foo(*args, **kwargs):
kwargs2 = map(rep_kwarg, kwargs.items())
it_combo = itertools.chain(args, kwargs2)
it_combo_str = map(str, it_combo)
arg_list = ', '.join(it_combo_str)
print("RESULT == ", repr(arg_list))
args = [98, 99, 100]
kwargs = {
"a": 1,
"b": 2,
"c": 3
}
foo(*args, **kwargs)
foo(98, 99, 100, a = 1, b = 2, c = 3)
控制台输出为:
RESULT == '98, 99, 100, a = 1, b = 2, c = 3'
RESULT == '98, 99, 100, a = 1, b = 2, c = 3'
这几乎可以满足您的要求:
def foo(*args, **kwargs):
print(args + tuple('{} = {}'.format(key,val) for key,val in kwargs.items()))