我们如何从 args 和 kwargs 打印参数列表?

How can we print the argument-list from args and kwargs?

假设我们有一个可变参数函数,如下所示:

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()))