向函数传递比最初的s更多的kwargs

2024-10-01 11:33:52 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以向函数发送比函数调用中调用的更多的Kargs?在

示例:

def mydef(a, b):
    print a
    print b

mydict = {'a' : 'foo', 'b' : 'bar'}
mydef(**mydict)    # This works and prints 'foo' and 'bar'

mybigdict = {'a' : 'foo', 'b' : 'bar', 'c' : 'nooooo!'}
mydef(**mybigdict)   # This blows up with a unexpected argument error

有没有什么方法可以不出错地传入mybigdict'c'在我的理想世界中,永远不会在mydef中使用,而且会被忽略。在

谢谢,我的挖掘没有找到我要找的东西。在

编辑:修正了一点代码。mydef(a, b, **kwargs)是我正在寻找的形式,但是inspect函数args对我来说是一个新事物,绝对是我工具箱的东西。谢谢大家!在


Tags: and方法函数示例foodefbarthis
2条回答

不,除非函数定义允许更多的参数(使用**kwargscatch all语法),否则不能调用参数超过定义的方法。在

您可以反省函数并删除它不接受的任何参数:

import inspect

mybigdict = {'a2' : 'foo', 'b2' : 'bar', 'c2' : 'nooooo!'}
argspec = inspect.getargspec(mydef)
if not argspec.keywords:
    for key in mybigdict.keys():
        if key not in argspec.args:
            del mybigdict[key]
mydef(**mybigdict)

我使用^{} function来检查可调用的是否通过.keywords支持**kwargcatch all,如果不支持,我使用.args信息删除该方法不支持的任何内容。在

为了澄清马蒂恩·皮尔特斯的答案(为了清楚起见)。如果将函数签名更改为:

def mydef(a, b, **kwargs):

这意味着不更改签名是不可能的。但如果这不是问题的话,那就行了。在

相关问题 更多 >