π§³ Python Arbitrary Arguments β Mastering *args
and **kwargs
π§² Introduction β Why Arbitrary Arguments Matter
When writing flexible, reusable functions, itβs often useful to accept any number of arguments. Python provides a simple and elegant way to do this with arbitrary arguments: *args
and **kwargs
.
These allow you to write functions that accept:
- π’ Any number of positional arguments using
*args
- π·οΈ Any number of keyword arguments using
**kwargs
This is essential for building libraries, decorators, and APIs where input parameters can vary.
π― In this guide, you’ll learn:
- How
*args
and**kwargs
work - When and why to use them
- Real-world examples
- Best practices and common pitfalls
π§ Syntax of Arbitrary Arguments
π *args
(Arbitrary Positional Arguments)
def function_name(*args):
for arg in args:
print(arg)
π·οΈ **kwargs
(Arbitrary Keyword Arguments)
def function_name(**kwargs):
for key, value in kwargs.items():
print(key, value)
π‘ You can use both in a function, but *args
must appear before **kwargs
.
β
Example 1: Using *args
def add_all(*numbers):
return sum(numbers)
print(add_all(2, 4, 6, 8))
π§ Output:
20
π Explanation:
All arguments are grouped into a tuple named numbers
.
β
Example 2: Using **kwargs
def print_user_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_user_info(name="Alice", age=30, city="New York")
Output:
name: Alice
age: 30
city: New York
π Explanation:
All named arguments are stored in a dictionary called info
.
π Combining *args
and **kwargs
def mixed_args(*args, **kwargs):
print("Positional:", args)
print("Keyword:", kwargs)
mixed_args(1, 2, 3, name="Bob", age=40)
Output:
Positional: (1, 2, 3)
Keyword: {'name': 'Bob', 'age': 40}
π‘ Tip: Always place *args
before **kwargs
in function definitions.
π Real-World Example: Configurable Logger
def log_message(level, *messages, **metadata):
print(f"[{level}] ", end="")
for msg in messages:
print(msg, end=" ")
if metadata:
print(f"| Metadata: {metadata}")
else:
print()
log_message("INFO", "User logged in", "ID=123", user="admin", role="superuser")
β Use Case: Useful for tools where you don’t know how much info you’ll receive.
β οΈ Common Pitfalls
Pitfall | Solution |
---|---|
Mixing *args and **kwargs improperly | Use *args before **kwargs |
Using default args after *args | Define defaults before *args |
Forgetting unpacking syntax | Use * and ** when calling functions |
π‘ Best Practices
- β
Name them
*args
and**kwargs
by convention (but names can vary) - β Use only when truly needed (donβt overuse!)
- β
Use unpacking (
*
and**
) when passing arguments to other functions - β Document what your function expects if using arbitrary inputs
π Summary β Key Takeaways
*args
gathers extra positional arguments into a tuple**kwargs
gathers extra keyword arguments into a dictionary- Perfect for dynamic APIs, decorators, and flexible utilities
- Maintain argument order:
normal
,*args
, default,**kwargs
β FAQ Section
β Can I change the names from args
and kwargs
?
Yes, but it’s recommended to stick to convention for clarity.
β What happens if I pass extra arguments without using *args
or **kwargs
?
Youβll get a TypeError
saying too many arguments were given.
β Can I unpack a list or dict when calling a function?
Yes!
func(*[1, 2, 3])
func(**{"name": "Alice", "age": 25})
β Can I use *args
without **kwargs
and vice versa?
Yes. Use whichever fits your use case.
Share Now :