ARGS
Collects extra positional arguments as a tuple
KWARGS
Collects extra named arguments as a dictionary
Basic example for args
def add_all(*args):
return sum(args)
print(add_all(1, 2, 3)) # 6
print(add_all(10, 20, 30, 40)) # 100
Basic example for kwargs
def print_user_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_user_info(name="Alice", age=30, country="USA")
**Output**
name: Alice
age: 30
country: USA
Using Both *args and **kwargs
def use_args_and_kwargs(*args, **kwargs):
print("Positional:", args)
print("Keyword:", kwargs)
use_args_and_kwargs(1, 2, 3, name="Bob", role="admin")
**Output**
Positional: (1, 2, 3)
Keyword: {'name': 'Bob', 'role': 'admin'}
Unpacking List and Dict into Function Call
def greet(name, age):
print(f"Hello {name}, age {age}")
args = ["Alice", 25]
kwargs = {"name": "Bob", "age": 30}
greet(*args)
greet(**kwargs)
**Output**
Hello Alice, age 25
Hello Bob, age 30
Note that args and kwargs are passed as *args and *kwargs to the greet function. If args is not passed as *args, the whole list ["Alice", 25] will be passed as the value for the name attribute, and **TypeError: greet() missing 1 required positional argument: 'age' * error is thrown
* in front of args and ** in front of kwargs unpacks each element in the list or dict as separate positional arguments
Use in Class Initialization
class User:
def __init__(self, name, **kwargs):
self.name = name
self.age = kwargs.get("age", None)
self.country = kwargs.get("country", "Unknown")
user = User("Alice", age=30)
print(user.name, user.age, user.country)
**Output**
Alice 30 Unknown
Dynamic Decorator with *args, **kwargs
def log_args(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args: {args} and kwargs: {kwargs}")
return func(*args, **kwargs)
return wrapper
@log_args
def describe_person(name, age, **details):
print(f"Name: {name}, Age: {age}")
for key, value in details.items():
print(f"{key.capitalize()}: {value}")
return f"{name} profile created."
# Call with positional and keyword arguments
result = describe_person("Alice", 30, country="USA", profession="Engineer")
print("Result:", result)
**Output**
Calling describe_person with args: ('Alice', 30) and kwargs: {'country': 'USA', 'profession': 'Engineer'}
Name: Alice, Age: 30
Country: USA
Profession: Engineer
Result: Alice profile created.
Complex JSON Generator with **kwargs
def generate_user(**kwargs):
return {
"id": kwargs.get("id"),
"profile": {
"name": kwargs.get("name"),
"email": kwargs.get("email")
}
}
user = generate_user(id=1, name="John Doe", email="[email protected]")
print(user)
**Output**
{
'id': 1,
'profile': {
'name': 'John Doe',
'email': '[email protected]'
}
}