Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 564
pablochacin Avatar asked Oct 21 '25 17:10

pablochacin


2 Answers

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)
like image 186
Devesh Kumar Singh Avatar answered Oct 24 '25 08:10

Devesh Kumar Singh


You can do it by creating an annotation like this

def printArgs(my_func):
    def wrapper(*arg, **kwargs):
        print("{}({})".format(my_func.__name__, ','.join([str(arg),str(kwargs)])))
        return my_func(*arg, **kwargs)
    return wrapper

@printArgs
def a_function_where_you_want_to_print_args(arg1, arg2, arg3="arg3"):
    pass

a_function_where_you_want_to_print_args(1,2, arg3="b")

This will print "a_function_where_you_want_to_print_args((1, 2),{'arg3': 'b'})"

like image 21
Xiidref Avatar answered Oct 24 '25 06:10

Xiidref



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!