How do I call a function and only pass it the arguments that it expects. For example say I have the following functions:
func1 = 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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With