Python *args and **kwargs: How to Write Flexible Functions

3D visualization of a function box accepting an unlimited stream of arguments, representing Python args and kwargs.

Sometimes you don’t know how many arguments a user might pass to your function, which is why understanding Python args and kwargs is essential. Think of the print() function. You can give it one thing: print("Hi"), or five things: print("Hi", name, age, score, date). How does it know how to handle both?

It uses special “unpacking” operators: * and **.These operators are crucial for managing Python args together with kwargs.

1. *args (Non-Keyword Arguments)

The single asterisk * lets a function accept any number of positional arguments. Python collects them all into a Tuple.

# The name 'args' is convention, but the '*' is what matters.
def add_all_numbers(*args):
    print(f"Received arguments: {args}")
    total = 0
    for num in args:
        total += num
    return total

print(add_all_numbers(5, 10))       # Output: 15
print(add_all_numbers(1, 2, 3, 4))  # Output: 10

2. **kwargs (Keyword Arguments)

The double asterisk ** lets a function accept any number of named (keyword) arguments. Python collects them into a Dictionary.

# 'kwargs' stands for Keyword Arguments
def create_profile(**kwargs):
    print(f"Received data: {kwargs}")
    for key, value in kwargs.items():
        print(f"{key.capitalize()}: {value}")

create_profile(name="Alice", age=25, job="Engineer")
# Output:
# Name: Alice
# Age: 25
# Job: Engineer

3. Using Both Together

You can combine them, but order matters! Standard arguments first, then *args, then **kwargs.

def versatile_function(standard_arg, *args, **kwargs):
    pass

This is extremely common when writing wrappers or decorators, as it allows your wrapper to pass any input through to the original function.

Similar Posts

Leave a Reply