Get a list/tuple/dict of the arguments passed to a function?

前端 未结 8 1147
梦如初夏
梦如初夏 2020-12-01 13:17

Given the following function:

def foo(a, b, c):
    pass

How would one obtain a list/tuple/dict/etc of the arguments passed in, wit

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 14:11

    I would use *args or **kwargs and throw an exception if the arguments are not as expected

    If you want to have the same errors than the ones checked by python you can do something like

    def check_arguments(function_name,args,arg_names):
        missing_count = len(arg_names) - len(args)
        if missing_count > 0:
            if missing_count == 1:
                raise TypeError(function_name+"() missing 1 required positionnal argument: "+repr(arg_names[-1]))
            else:
                raise TypeError(function_name+"() missing "+str(missing_count)+" required positionnal argument: "+", ".join([repr(name) for name in arg_names][-missing_count:-1])+ " and "+repr(arg_names[-1]))
    

    using with somethin like

    def f(*args):
        check_arguments("f",args,["a","b","c"])
        #whatever you want
        ...
    

提交回复
热议问题