Decorator to print function call details - parameters names and effective values

前端 未结 5 604
失恋的感觉
失恋的感觉 2020-12-05 05:46

I want to make a function that being a decorator to another function will print that function call details - parameters names and effective values. My current implementation

5条回答
  •  眼角桃花
    2020-12-05 05:58

    Sorry its a bit messy. I modified some code from http://wiki.python.org/moin/PythonDecoratorLibrary#Easy_Dump_of_Function_Arguments

    def dump_args(func):
        "This decorator dumps out the arguments passed to a function before calling it"
        argnames = func.func_code.co_varnames[:func.func_code.co_argcount]
        fname = func.func_name
        def echo_func(*args,**kwargs):
            print fname, "(", ', '.join(
                '%s=%r' % entry
                for entry in zip(argnames,args[:len(argnames)])+[("args",list(args[len(argnames):]))]+[("kwargs",kwargs)]) +")"
        return echo_func
    
    @dump_args
    def test(a, b = 4, c = 'blah-blah', *args, **kwargs):
        pass
    

    test(1, 2, 3, 4, 5, d = 6, g = 12.9)

    output:

    test ( a=1, b=2, c=3, args=[4, 5], kwargs={'d': 6, 'g': 12.9})

提交回复
热议问题