Python convert args to kwargs

前端 未结 6 1043
南方客
南方客 2021-02-05 07:57

I am writing a decorator that needs to call other functions prior to call of the function that it is decorating. The decorated function may have positional arguments, but the f

6条回答
  •  遥遥无期
    2021-02-05 08:11

    Note - co_varnames will include local variables as well as keywords. This probably won't matter, as zip truncates the shorter sequence, but may result in confusing error messages if you pass the wrong number of args.

    You can avoid this with func_code.co_varnames[:func_code.co_argcount], but better is to use the inspect module. ie:

    import inspect
    argnames, varargs, kwargs, defaults = inspect.getargspec(func)
    

    You may also want to handle the case where the function defines **kwargs or *args (even if just to raise an exception when used with the decorator). If these are set, the second and third result from getargspec will return their variable name, otherwise they will be None.

提交回复
热议问题