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
352 views
in Technique[技术] by (71.8m points)

python - Unpacking keyword arguments, but only the ones that match the function

Let's say I have a function:

def foo(a=None, b=None, c=None):
  return "a:%s, b:%s, c:%s" % (a, b, c)

I have a dictionary with some (or none) of the arguments above, but also with keys that are not named arguments in the function, e.g.:

d = {'a': 1, 'x': 4, 'b': 2, 'y': 5}

If I call the following I will get an error, because 'x' and 'y' are not keyword arguments in the foo function.

foo(**d)  # error

Is there an elegant way of passing the arguments from a dictionary to a function, but only those values with keys that match the function arguments.

Please correct me if my argument/parameter terminology is off.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
def foo(a = None, b=None, c=None,**extras):
    return "a:%s, b:%s, c:%s" % (a, b, c)

here the **extras will collect all the extra named/keyword arguments.


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

...