?Introduction
You might have a code in Python such that certain functions have no arguments, whereas the others have numerous arguments. While there are times, we have functions with arguments unknown. Thus, we may have n number of arguments in a function, and sometimes we don’t even have a clue about the input size of the function. Therefore, in this tutorial, you will learn about different methods to count the number of Function Arguments in Python.
?️ Let us first understand “what are function arguments?”
Assuming a function is defined with the parameters, we need to pass some arguments to these parameters. Hence, function arguments are the input values that are passed to the parameters of the function definition.
Example: Consider the following example where you want to add to numbers and then subtract them from a third number.
# Adding two numbers def add(a, b): return a + b # subtracting third number def calc(c, d): return c - d # Main program print("Enter 3 numbers:") a = float(input("Number 1:")) b = float(input("Number 2:")) c = float(input("Number 3:")) # Now Calculate the sum x = add(a, b) # Now calculate the result; res = calc(c, x) # Print the result print("Result is {}".format(res))
Output:
Enter 3 numbers: Number 1:25 Number 2:15 Number 3:75 Result is 35.0
Explanation: In the above example
- Functions Defined
add(a, b)
calc(c, d)
- Parameters:
a,b
foradd
functionc,d
forcalc
function
- Arguments:
num1
andnum2
–>x = add(num1, num2)
num3
andx
–>res = calc(num3, x)
Now that you know what function arguments are, let’s look at the numerous methods that allow us to count the number of Function Arguments in Python.
?Method 1: Using the len() function in *args
In Python, *args is used to allow an arbitrary number of non-keyword arguments within a function.
Example:
def average(*args): return sum(args) / len(args) print(average(999.0, 966.3, 988.2, 1344.5)) # 1074.5
Now, assume that we want to write a function that will accept an arbitrary number of strings and then return the number of the arguments passed into the function.
def lenarg(*args): # Using len() to count the no. of arguments length = len(args) print("Arguments Passed: ") for i in args: print(i) return length x = lenarg('Rashi', 'Shubham', 'Chris', 'Maricar', 'Max') print("Total Number of Arguments = {}".format(x))
Output:
Arguments Passed: Rashi Shubham Chris Maricar Max Total Number of Arguments = 5
Explanation: *args allowed us to pass an arbitrary number of arguments within the function and the len() method helped us to count the actual number of arguments passed.
✏️ NOTE: Python’s built-in function len()
returns the length of the given string, array, list, tuple, dictionary, or any other iterable. The type of the return value is an integer that represents the number of elements in this iterable.
- Related Articles:
Example 2: Let us have a look at another example where the function accepts three different number of arguments and computes them accordingly.
def lenarg(*arguments): length = len(arguments) # We will count the total arguments using len() return length # Returning the length of arguments print("The total arguments in each case are:") # Different no. of arguments passed print("No. of arguments in case 1: ", lenarg(1, 2, 3, 4, 5)) print("No. of arguments in case 2: ", lenarg(2.4, 4.5, 5.6, 9.0)) print("No. of arguments in case 3: ", lenarg('Python', 'Golang', 'Java'))
Output:
The total arguments in each case are: No. of arguments in case 1: 5 No. of arguments in case 2: 4 No. of arguments in case 3: 3
?Method 2- Using the len() and **kwargs
If you are uncertain about how many keyword arguments have to be passed to a function in the program, then you can use an argument with the double asterisks as a prefix to the argument which allows us to pass an arbitrary number of keyword arguments into our function. This allows the function to receive a dictionary of arguments and it can then access the items accordingly.
Read more here:- Python Double Asterisk (**)
Note:
- *args are used to receive multiple arguments as a tuple.
- **kwargs are used to receive multiple keyword arguments as a dictionary.
def count(**kwargs): length = len(kwargs) return length x = count(Hello=1, Welcome=2, to=3, Finxter=4) print("Count of Arguments = {}".format(x))
Output:
Count of Arguments = 4
?Method 3: Using the signature function
If you are using Python 3.0 or above, you can opt for the Signature
class to find the total number of arguments within a function signature.
✨ Note:
- The call signature of a callable object and its return annotation is represented by the Signature object . To fetch the Signature object, you can use the
signature()
function. - You can use
sig.parameters
to retrieve a mapping of attribute names to parameter objects. - Further, to find the number of arguments in the function you can use
len(sig.parameters)
.
Example:
from inspect import signature def someMethod(a,b,c): pass sig = signature(someMethod) params = sig.parameters print("Arguments: ", sig) print("No. of Arguments: ", len(params))
Output:
Arguments: (a, b, c) No. of Arguments: 3
?Method 4: Using sys.argv()
In Python, sys.argv()
is used while working with command line arguments. Command line arguments are the values passed while we call the program alongside the calling statement. Basically, sys.argv()
is an array for command line arguments in Python. To utilize this, a module named “sys” has to be imported.
This is how sys.argv
works:
import sys print("The name of the program is:", sys.argv[0]) print("The arguments are:", str(sys.argv))
Output:
The name of the program is: countArg.py The arguments are: ['countArg.py']
Now let’s look at an example of how sys.argv()
is used to count the number of arguments:
print("The name of the program is: ",sys.argv[0]) print("Total count of arguments passed: ",(len(sys.argv) - 1)) print("The arguments are: ",str(sys.argv))
Output:
C:\Users\DELL\Desktop>Python countArg.py 100 200 300 400 500 The name of the program is: countArg.py Total count of arguments passed: 5 The arguments are: ['countArg.py', '100', '200', '300', '400', '500']
Explanation:
- Always remember that
argv[0]
is the name of the program. - You must call
sys.argv()
using your program name followed by the arguments as shown in the output. len(sys.argv)-1
gives us the number of arguments passed through command line. Since theargv[0]
always stores the name of the program; hence you have to subtract 1 from the entire length of the list to get the actual count of arguments passed through the command line.
?Method 5
How will you compute the number of arguments in your function if you have a code with a certain function as shown below?
def foo(a, b, c=1, *arg, j=2, k=3, **kwargs): pass count_args = foo(100, 200, 300, 10, 20, l='Harry', m='Potter')
To solve the above problem, you will need the help of following:
func.__code__.co_argcount
allows you to fetch the number of arguments BEFORE*args
func.__kwdefaults__
gives you a dict of the keyword arguments AFTER*args
func.__code__.co_kwonlyargcount
is the same aslen(func.__kwdefaults__)
Now we have all the tools to count the number of arguments in the function. Without further delay let us compute the result in the following example:
def foo(a, b, c=1, *arg, j=2, k=3, **kwargs): len_before_args = foo.__code__.co_argcount len_after_args = foo.__code__.co_kwonlyargcount print("Number of arguments BEFORE *args: ", foo.__code__.co_argcount) # print("dict of the keyword arguments AFTER *args: ", foo.__kwdefaults__) print("Number of keyword arguments AFTER *args: ", foo.__code__.co_kwonlyargcount) # print("values of optional arguments before *args: ", foo.__defaults__) print("Number of arguments passed to *arg: ", len(arg)) print("Number of arguments passed to **kwargs: ",len(kwargs)) return len_before_args + len_after_args + len(arg) + len(kwargs) count_args = foo(100, 200, 300, 10, 20, l='Harry', m='Potter') print("Total No. of arguments: ", count_args)
Output:
Passing values to the function: Number of arguments BEFORE *args: 3 Number of keyword arguments AFTER *args: 2 Number of arguments passed to *arg: 2 Number of arguments passed to **kwargs: 2 Total No. of arguments: 9
?Conclusion
I hope this article helped you to learn different methods to count the number of Function Arguments in Python. Please subscribe and stay tuned for more interesting articles in the future. Happy learning!
✍️ Post Credit: Shubham Sayon and Rashi Agarwal
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
Get your copy of Python One-Liners here.