Advanced Arguments: *args and **kwargs
When you don't know ahead of time how many arguments a user might pass into a function, `*args` and `**kwargs` provide the solution.
What is it?
• `*args`: Collects positional arguments into a `tuple`. • `**kwargs`: Collects keyword arguments into a `dict`.
Why is it used?
Used in decorators, wrapper functions, logging utilities, and flexible framework APIs (like Flask route decorators).
Detailed Explanation
The asterisk `*` and double asterisk `**` are the actual unpacking operators (the names `args` and `kwargs` are convention).
Argument Order in Function Definitions:
1. Standard positional parameters
2. `*args`
3. Default parameters
4. `**kwargs`
Syntax Structure
Syntax Blueprint
def func(required, *args, **kwargs):
# args is a tuple
# kwargs is a dict
Code Example
PYTHON Code
# Flexible Course Enrollment Handler
def register_student(student_name, *courses, **extra_details):
print(f"\nRegistering Student: {student_name}")
print(f"Enrolled Courses ({len(courses)}): {', '.join(courses)}")
if extra_details:
print("Additional Details:")
for key, val in extra_details.items():
print(f" • {key.title()}: {val}")
# Calling with arbitrary positional courses and arbitrary keyword details
register_student(
"Mahesh Kulkarni",
"Advanced Python",
"Data Analytics",
"Excel",
phone="9876543210",
city="Nanded",
referral="LinkedIn"
)
Explanation of the Code
• `student_name` captures the first argument.
• `*courses` packs the 3 course strings into a tuple.
• `**extra_details` packs `phone`, `city`, and `referral` into a dictionary.
Expected Output
Registering Student: Mahesh Kulkarni
Enrolled Courses (3): Advanced Python, Data Analytics, Excel
Additional Details:
• Phone: 9876543210
• City: Nanded
• Referral: LinkedIn
Real-World Application
Used across Python decorators, database ORM queries, and Flask `app.route()` implementations.
Common Mistakes to Avoid
• Placing positional arguments after `*args` or `**kwargs` in the function signature (causes syntax error).
• Forgetting that `args` is a tuple, not a list.
Quick Practice Challenge
Write a function `sum_all(*numbers)` that sums any quantity of passed numbers.
Key Takeaways
• `*args` packs variable positional arguments into a tuple.
• `**kwargs` packs variable keyword arguments into a dictionary.
• Essential for building reusable decorators and utility functions.