Python将args转换为kwargs [英] Python convert args to kwargs

查看:118
本文介绍了Python将args转换为kwargs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个装饰器,需要在装饰它的函数调用之前调用其他函数。装饰的函数可能具有位置参数,但是装饰器将调用的函数只能接受关键字参数。有没有人可以方便地将位置参数转换为关键字参数?

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 functions the decorator will call can only accept keyword arguments. Does anyone have a handy way of converting positional arguments into keyword arguments?

我知道我可以得到修饰函数的变量名列表:

I know that I can get a list of the variable names of the decorated function:

>>> def a(one, two=2):
...    pass

>>> a.func_code.co_varnames
('one', 'two')

但是我可以

我的装饰器看起来像这样:

My decorator looks like this:

class mydec(object):
    def __init__(self, f, *args, **kwargs):
        self.f = f

    def __call__(self, *args, **kwargs):
        hozer(**kwargs)
        self.f(*args, **kwargs)

除了比较kwargs和co_varnames,向kwargs添加任何不存在的东西,并希望达到最佳效果之外,还有其他方法吗?

Is there a way other than just comparing kwargs and co_varnames, adding to kwargs anything not in there, and hoping for the best?

推荐答案

注意-co_varnames将包含局部变量以及关键字。这可能无关紧要,因为zip会截短较短的序列,但是如果您传递错误数量的args,则可能导致混乱的错误消息。

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.

func_code.co_varnames [:func_code.co_argcount] ,但最好使用检查模块。即:

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)

您可能还想处理函数定义 ** kwargs * args (即使与装饰器一起使用时也会引发异常)。如果设置了这些,则 getargspec 的第二个和第三个结果将返回其变量名,否则将为None。

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.

这篇关于Python将args转换为kwargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆