你能列出函数接收的关键字参数吗? [英] Can you list the keyword arguments a function receives?

查看:21
本文介绍了你能列出函数接收的关键字参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,我需要将键/值作为关键字参数传递.. 例如..

d_args = {'kw1': 'value1', 'kw2': 'value2'}示例(** d_args)

这很好用,但是如果 d_args dict 中有不被 example 函数接受的值,它显然会死.说,如果 example 函数定义为 def example(kw2):

这是一个问题,因为我不控制 d_argsexample 函数的生成.它们都来自外部模块,而 example 只接受字典中的一些关键字参数..

理想情况下我会这样做

parsed_kwargs = feedparser.parse(the_url)valid_kwargs = get_valid_kwargs(parsed_kwargs,valid_for = PyRSS2Gen.RSS2)PyRSS2Gen.RSS2(**valid_kwargs)

我可能只是从有效关键字参数列表中过滤字典,但我想知道:有没有办法以编程方式列出特定函数采用的关键字参数?>

解决方案

比直接检查代码对象并计算变量更好一点的是使用检查模块.

<预><代码>>>>进口检验>>>def func(a,b,c=42, *args, **kwargs): 通过>>>检查.getargspec(函数)(['a', 'b', 'c'], 'args', 'kwargs', (42,))

如果你想知道它是否可以用一组特定的参数调用,你需要没有指定默认值的参数.这些可以通过以下方式获得:

def getRequiredArgs(func):args, varargs, varkw, defaults = inspect.getargspec(func)如果默认:args = args[:-len(defaults)]return args # *args 和 **kwargs 不是必需的,所以忽略它们.

然后有一个函数可以告诉您在特定的 dict 中缺少什么:

def missingArgs(func, argdict):返回集(getRequiredArgs(func)).difference(argdict)

同样,要检查无效参数,请使用:

def invalidArgs(func, argdict):args, varargs, varkw, defaults = inspect.getargspec(func)if varkw: return set() # 全部接受返回集(argdict) - 集(args)

所以一个完整的测试是否可以调用是:

def isCallableWithArgs(func, argdict):返回 not missingArgs(func, argdict) 和 not invalidArgs(func, argdict)

(这仅适用于 python 的 arg 解析.显然无法检测到任何运行时检查 kwargs 中的无效值.)

I have a dict, which I need to pass key/values as keyword arguments.. For example..

d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)

This works fine, but if there are values in the d_args dict that are not accepted by the example function, it obviously dies.. Say, if the example function is defined as def example(kw2):

This is a problem since I don't control either the generation of the d_args, or the example function.. They both come from external modules, and example only accepts some of the keyword-arguments from the dict..

Ideally I would just do

parsed_kwargs = feedparser.parse(the_url)
valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2)
PyRSS2Gen.RSS2(**valid_kwargs)

I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: Is there a way to programatically list the keyword arguments the a specific function takes?

解决方案

A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.

>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))

If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by:

def getRequiredArgs(func):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if defaults:
        args = args[:-len(defaults)]
    return args   # *args and **kwargs are not required, so ignore them.

Then a function to tell what you are missing from your particular dict is:

def missingArgs(func, argdict):
    return set(getRequiredArgs(func)).difference(argdict)

Similarly, to check for invalid args, use:

def invalidArgs(func, argdict):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if varkw: return set()  # All accepted
    return set(argdict) - set(args)

And so a full test if it is callable is :

def isCallableWithArgs(func, argdict):
    return not missingArgs(func, argdict) and not invalidArgs(func, argdict)

(This is good only as far as python's arg parsing. Any runtime checks for invalid values in kwargs obviously can't be detected.)

这篇关于你能列出函数接收的关键字参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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