如何打印 args 和 kwargs 的列表

pab*_*cin 2 python formatting keyword-argument

在我的代码中,我有很多地方将一个函数及其参数传递给另一个函数。出于调试目的,我想打印函数的名称和参数列表。例如

def process(f, *args, **kwargs):
    print("processing " + print_func(f, args, kwargs))
Run Code Online (Sandbox Code Playgroud)

的预期输出 process(myfunc, 1,2, a="A",b=0)应该是"processing myfunc(1,2,a="A", b=0)"

我在打印args如下方面取得了一些进展:

def print_func(f, *args, **kwarg):
    func_str = f.__name__ + "("
    if len(args) > 0:
        func_str = func_str + (', '.join(['%.2f']*len(x)) % args)
     func_str = func_str + ")"
Run Code Online (Sandbox Code Playgroud)

在上面的例子中将产生输出 processing myfunc(1,2)

我的问题是如何打印 kwargs。我无法找到类似的解决方案,使用动态格式字符串将其打印k=v为由“,”分隔的对序列。

任何建议将不胜感激。

Dev*_*ngh 5

要格式化argsand kwargs,您可以简单地迭代它们并创建您的字符串表示

def process(my_func, *args, **kwargs):

    #Iterate over all args, convert them to str, and join them
    args_str = ','.join(map(str,args))

    #Iterater over all kwargs, convert them into k=v and join them
    kwargs_str = ','.join('{}={}'.format(k,v) for k,v in kwargs.items())

    #Or using f-strings
    #kwargs_str = ','.join(f'{k}={v}' for k,v in kwargs.items()

    #Form the final representation by adding func name
    return "processing {}({})".format(my_func.__name__, ','.join([args_str,kwargs_str]))

    #Or using f-strings
    #return f"processing {my_func.__name__}({','.join([args_str,kwargs_str])})"

print(process(my_func, 1,2, a="A",b=0))
Run Code Online (Sandbox Code Playgroud)

输出将是

processing my_func(1,2,a=A,b=0)
Run Code Online (Sandbox Code Playgroud)