Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 735
bradley.ayers Avatar asked Apr 04 '11 20:04

bradley.ayers


2 Answers

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]))
like image 183
Sven Marnach Avatar answered Sep 22 '22 04:09

Sven Marnach


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).

like image 43
Michael Hoffman Avatar answered Sep 22 '22 04:09

Michael Hoffman