Python将args转换为kwargs

编程入门 行业动态 更新时间:2024-10-16 02:22:08
本文介绍了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

本文发布于:2023-11-24 00:10:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623267.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   Python   args   kwargs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!