Python is a language that values simplicity and flexibility, and nowhere is that more evident than in how it handles function arguments. If you’ve ever come across *args and **kwargs and wondered, “What’s going on here?” — you’re in the right place.
Let’s break it down with plain English, some real examples, and use cases you’ll actually run into in real projects.
What Are *args and **kwargs?
In Python functions:
*argslets you pass a variable number of positional arguments.**kwargslets you pass a variable number of keyword arguments.
They sound similar, but they behave a bit differently.
*args: Flexible Positional Arguments
Imagine you’re building a shopping cart function:
def add_to_cart(*items):
for item in items:
print(f"Adding {item} to cart")
add_to_cart("Apples", "Bananas", "Oranges")
Output:
Adding Apples to cart
Adding Bananas to cart
Adding Oranges to cart
Here, *items collects all positional arguments into a tuple. You don’t have to know how many items in advance — super handy!
**kwargs: Flexible Keyword Arguments
Now let’s say you want to accept different product details like name and price:
def show_product_details(**details):
for key, value in details.items():
print(f"{key}: {value}")
show_product_details(name="Laptop", price=1200, warranty="2 years")
Output:
name: Laptop
price: 1200
warranty: 2 years
Here, **details grabs all keyword arguments and packs them into a dictionary. It’s great for flexible configurations or optional settings.
Can You Use Both Together?
Yes, and it’s super powerful.
def complete_order(*items, **order_info):
print("Items:", items)
print("Order Info:", order_info)
complete_order("Laptop", "Mouse", order_id=123, user="nagesh")
Output:
Items: ('Laptop', 'Mouse')
Order Info: {'order_id': 123, 'user': 'nagesh'}
Just remember: *args comes before **kwargs in the function definition.
Why Should You Care?
These are must-know tools for:
- Writing reusable, clean functions
- Creating decorators
- Building APIs or utilities that adapt to different use cases
- Handling flexible data in data engineering or ML pipelines
🚫 A Few Common Pitfalls
- Don’t name
argsorkwargsanything special — they’re just convention.*thingsand**stuffwork too. - Be cautious when mixing them with regular parameters — keep the order:
def fun(positional, *args, keyword_default=val, **kwargs)
🎯 Real-World Use Case in Data Engineering
Let’s say you’re writing a logging function for your ETL job:
def log_event(event_type, *args, **kwargs):
print(f"[{event_type}] -", *args)
if kwargs:
print("Metadata:", kwargs)
log_event("START", "Job XYZ", timestamp="2025-04-06", user="admin")
Boom! You’ve built a flexible logger you can use across your pipeline.
Leave a comment