Checking the number of arguments a function takes - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Checking the number of arguments a function takes (/thread-34198.html) |
Checking the number of arguments a function takes - Chirumer - Jul-06-2021 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) RE: Checking the number of arguments a function takes - deanhystad - Jul-06-2021 I prefer catching the exception over trying to predict all possible failures. try: user_func(information, extra_information) except TypeError: user_func(informationn) RE: Checking the number of arguments a function takes - Gribouillis - Jul-06-2021 from inspect import signature nparams = len(signature(user_func).parameters)Finer details can be obtained by examining the information provided by the Parameter objects. RE: Checking the number of arguments a function takes - Chirumer - Jul-06-2021 Thanks deanhystad and Gribouillis I found both your suggestions helpful |