12. Argument Count
By Bernd Klein. Last modified: 19 Feb 2025.
Introduction
Have you ever wondered, "How can I determine the number of arguments in a Python function?" If you're a newcomer to Python, it's unlikely that such a query would even cross your mind. You might simply ask, "What's the point?" or "Why bother". The solution is straightforward: you can either analyze the code or refer to the documentation.
As your proficiency in Python increases, and when you delve into advanced topics like decorators, composing of functions or currying, things look different. You begin crafting code for functions that are unknown at the time of writing So there is no direct way to look at "the function".
Live Python training
See our Python training courses
An Example
As an example, you can examine the following code for a decorator that tracks how many times a function has been invoked, regardless of the function's argument count or the specific arguments passed to the 'wrapper' function.
def call_counter(func):
def wrapper(*args, **kwargs):
helper.calls += 1
return func(*args, **kwargs)
helper.calls = 0
return helper
Let's define the following functions:
def greet(name):
return f"Hello, {name}!"
def calculate_rectangle_area(length, width):
return length * width
def calculate_surface_area(length, width, height):
return 2 * (length * width + width * height + height * length)
def display_info(name, age, *args, **kwargs):
print(f"Name: {name}")
print(f"Age: {age}")
print("Additional Info:")
for info in args:
print(info)
print("Keyword Arguments:")
for key, value in kwargs.items():
print(f"{key}: {value}")
Now we decorate these functions with the following decorator:
def describe_parameters(func):
def wrapper(*args, **kwargs):
print(f'{args=}, {kwargs=}')
print(f'{len(args)=}, {len(kwargs)=}')
return func(*args, **kwargs)
return wrapper
greet = describe_parameters(greet)
calculate_rectangle_area = describe_parameters(calculate_rectangle_area)
calculate_surface_area = describe_parameters(calculate_surface_area)
display_info = describe_parameters(display_info)
print(greet('Mike'))
OUTPUT:
args=('Mike',), kwargs={}
len(args)=1, len(kwargs)=0
Hello, Mike!
