Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...