Python Forum

Full Version: Checking the number of arguments a function takes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
user_func is a function with either 1 or 2 parameters.
What's the best way to call the function with 2 parameters if it supports it, or call it with 1 parameter if not?

Here is one way I found..
def caller(user_func):
        # user_func has either 1 or 2 parameters

    information = 'some information'
    extra_information = 'some other information'

    if user_func.__code__.co_argcount == 2:
            # if function has 2 parameters
        user_func(information, extra_information)
    else:
            # function has 1 parameter
        user_func(information)
I prefer catching the exception over trying to predict all possible failures.
try:
    user_func(information, extra_information)
except TypeError:
    user_func(informationn)
from inspect import signature
nparams = len(signature(user_func).parameters)
Finer details can be obtained by examining the information provided by the Parameter objects.
Thanks deanhystad and Gribouillis
I found both your suggestions helpful