Python Forum
Checking the number of arguments a function takes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Checking the number of arguments a function takes
#1
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)
Reply
#2
I prefer catching the exception over trying to predict all possible failures.
try:
    user_func(information, extra_information)
except TypeError:
    user_func(informationn)
Chirumer likes this post
Reply
#3
from inspect import signature
nparams = len(signature(user_func).parameters)
Finer details can be obtained by examining the information provided by the Parameter objects.
Chirumer likes this post
Reply
#4
Thanks deanhystad and Gribouillis
I found both your suggestions helpful
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Class takes no arguments bily071 2 598 Oct-23-2023, 03:59 PM
Last Post: deanhystad
  calling external function with arguments Wimpy_Wellington 7 1,344 Jul-05-2023, 06:33 PM
Last Post: deanhystad
  Error TypeError: output_type_handler() takes 2 positional arguments but 6 were given paulo79 1 1,858 Oct-17-2022, 06:29 PM
Last Post: paulo79
  'namespace' shorthand for function arguments? shadowphile 5 2,541 Aug-11-2021, 09:02 PM
Last Post: shadowphile
  Possible to dynamically pass arguments to a function? grimm1111 2 2,126 Feb-21-2021, 05:57 AM
Last Post: deanhystad
  is there a single function to confine a number between two others? Skaperen 7 2,761 Nov-28-2020, 06:10 PM
Last Post: Skaperen
  Why is the function returning None for a * b instead of number? omm 10 4,202 Nov-05-2020, 01:17 PM
Last Post: omm
  Class Takes No Arguments horuscope42 4 4,754 Oct-26-2020, 11:10 PM
Last Post: not_username1234
  RuntimeError: Optimal parameters not found: Number of calls to function has reached m bntayfur 0 6,073 Aug-05-2020, 04:41 PM
Last Post: bntayfur
  basic random number generator in replace function krug123 2 2,006 Jul-31-2020, 01:02 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020