Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

python - Passing more kwargs into a function than initially set

Is there a way to send more kwargs into a function than is called for in the function call?

Example:

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

Is there any way to pass in mybigdict without the error? 'c' would never be used in mydef in my ideal world and would just be ignored.

Thanks, my digging has not come up with what I am looking for.

Edit: Fixed the code a bit. The mydef(a, b, **kwargs) was the form that I was looking for, but the inspect function args was a new thing to me and definitely something for my toolbox. Thanks everyone!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, unless the function definition allows for more parameters (using the **kwargs catch-all syntax), you cannot call a method with more arguments than it has defined.

You can introspect the function and remove any arguments it won't accept however:

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)

I'm using the inspect.getargspec() function to check if the callable supports a **kwarg catch-all via .keywords, and if it doesn't, I use the .args information to remove anything the method won't support.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...