Search code examples
pythonreflectionintrospectioninspect

Passing arguments to functions in Python using inspect


I have a Python script which creates a dictionary of its own functions and I'd like it to execute them by reading in a function name and arguments using YARP (knowledge of YARP is irrelevant to this question though).

I create a list of strings called "inc" which is populated by values coming into the program. The first item is a function name, and any other strings in the list are arguments. I create a dictionary called "methods" where the key is the function name and the value is a reference to the function object (using the inspect module). I store the return value of the function in a variable "result".

The snippet below shows a simplified version of what I'm using so far, which works fine, but can't handle functions with more than one argument. To circumvent this I use a list if a function needs more parameters:

if len(inc) == 1:
    result = methods[inc[0]]()   # call method with 0 arguments

elif len(inc) == 2:
    result = methods[inc[0]](inc[1])    # call method passing a string

else:
    args = []
    result = methods(inc[0])(inc[1:])    # call method passing a list

Ideally, I'd like to change this so that my functions can have any number of arguments, but I can't figure out how I can do this. I'm new to Python and I have looked at the documentation and various websites - I just can't find a solution. I've tried things like creating a tuple of the arguments, but that doesn't work either as it ends up passing the whole tuple in as one parameter.

Is there a better solution to this problem, like creating some kind of object which represents a set of parameters and passing that into the function? Any suggestions would be greatly appreciated!


Solution

  • You should check out https://stackoverflow.com/a/3394898/1395668.

    The magic you are looking for is the *. Apply this to your list and it unpacks the items into the argument fields of your function:

    a = [ 1, 2, 3]
    def myfunc(a, b, c):
        return a + b + c
    
    print myfunc(*a)
    

    Check out ** for the same approach for dict