Search code examples
pythonintrospection

How do I figure out what the named arguments to a function are in python


I am writing a function that is going to take, as one of it's arguments, a dictionary of functions to apply. All of these functions will have at least one argument in common, but some will have others. Without losing the flexibility of letting the user specify arbitrary functions (conditional on having their arguments in scope), how can I introspect a function to see what its arguments are?

Here's a dummy example:

def f1(x, y):
    return x+y

def f2(x):
    return x**2

fundict = dict(f1 = f1,
               f2 = f2)

y = 3 # this will always be defined in the same scope as fundict

for i in list(fundict.keys()):
    if <the args to the function have y in them>:
        fundict[i](x, y)
    else:
        fundict[i](x)

Even better would be something that programmatically looks at the definition of the function and feeds the array of arguments to it, conditional on them being in-scope.

I'd also appreciate good general suggestions for different ways to go about solving this problem, that might not involve introspecting a function.


Solution

  • You can use inspect.getfullargspec

    import inspect
    
    def f1(x, y):
        return x+y
    
    def f2(x):
        return x**2
    
    fundict = dict(f1 = f1,
                   f2 = f2)
    
    y = 3 # this will always be defined in the same scope as fundict
    
    x = 1
    
    for i in list(fundict.keys()):
        if 'y' in inspect.getfullargspec(fundict[i]).args:
            print(fundict[i](x, y))
        else:
            print(fundict[i](x))
    

    This gives:

    4
    1