Search code examples
pythonformattingkeyword-argument

How to print the list of args and kwargs


In my code, I have many places where I pass a function and its arguments to another function. For debugging purposes, I want to print the name of the function and the list of arguments. For example

def process(f, *args, **kwargs):
    print("processing " + print_func(f, args, kwargs))

The expected output for process(myfunc, 1,2, a="A",b=0) should be "processing myfunc(1,2,a="A", b=0)"

I made some progress printing the args as follows:

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 + ")"

which in the example above will produce the output processing myfunc(1,2)

The problem I have is how to print the kwargs. I can't figure out a similar solution using a dynamic formatting string for printing it as a sequence of k=v pairs separated by ",".

Any suggestion would be appreciated.


Solution

  • To format args and kwargs, you can simply iterate over them and create your string representation

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

    The output will be

    processing my_func(1,2,a=A,b=0)