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

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

问题描述

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

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)

这很好用,但是,如果d_args字典中有一些example函数不接受的值,显然就死了..说,如果示例函数定义为

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):

这是一个问题,因为我无法控制d_argsexample函数的生成.它们都来自外部模块,并且example仅接受来自该命令.

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..

理想情况下我会做

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?

推荐答案

比直接检查代码对象并计算变量要好得多的方法是使用inspect模块.

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,))

如果您想知道它是否可以与一组特定的args一起调用,则需要未指定默认值的args.这些可以通过以下方式获得:

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)

(这仅对python的arg解析是有好处的.任何运行时检查kwargs中的无效值显然都无法检测到.)

(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天全站免登陆