I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their appropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form {Keyword:(FunctionName, AmountofArguments)}
.
This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.
We will use the special syntax called *args that is used in the function definition of python. Syntax *args allow us to pass a variable number of arguments to a function. We will use len() function or method in *args in order to count the number of arguments of the function in python.
To extract the number and names of the arguments from a function or function[something] to return ("arg1", "arg2"), we use the inspect module. The given code is written as follows using inspect module to find the parameters inside the functions aMethod and foo.
Luckily, you can write functions that take in more than one parameter by defining as many parameters as needed, for example: def function_name(data_1, data_2):
length property provides the number of arguments actually passed to a function.
inspect.getargspec():
Get the names and default values of a function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.
What you want is in general not possible, because of the use of varargs and kwargs, but inspect.getargspec
(Python 2.x) and inspect.getfullargspec
(Python 3.x) come close.
Python 2.x:
>>> import inspect >>> def add(a, b=0): ... return a + b ... >>> inspect.getargspec(add) (['a', 'b'], None, None, (0,)) >>> len(inspect.getargspec(add)[0]) 2
Python 3.x:
>>> import inspect >>> def add(a, b=0): ... return a + b ... >>> inspect.getfullargspec(add) FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=(0,), kwonlyargs=[], kwonlydefaults=None, annotations={}) >>> len(inspect.getfullargspec(add).args) 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With