开发者

Call a function in Python and pass only the arguments it expects

How do I call a function and only pass it the arguments that it expects. For example say I have the following functions:

func1开发者_如何学Go = lambda a: True
func2 = lambda a, b: True
func3 = lambda c: True

I want some Python code that is able to successfully call these functions without raising a TypeError by passing unexpected arguments. i.e.

kwargs = dict(a=1, b=2, c=3)
for func in (func1, func2, func3):
    func(**kwargs)  # some magic here

I'm not interested in just adding **kwargs to the functions when I define them.


You can use inspect.getargspec():

from inspect import getargspec
kwargs = dict(a=1, b=2, c=3)
for func in (func1, func2, func3):
    func(**dict((name, kwargs[name]) for name in getargspec(func)[0]))


Well, depending on exactly what you will want to do with variable arguments and keyword arguments, the result will be a little different, but you probably want to start with inspect.getargspec(func).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜