The *args parameter in a function allows you to pass a variable number of positional arguments. Inside the function, args will be a tuple containing all the positional arguments passed to the function.
def sum_all(*args):
total = 0
for num in args:
total += num
return total
# Example usage
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(10, 20, 30, 40)) # Output: 100In this example:
sum_allaccepts any number of arguments (*args).- Inside the function,
argsbecomes a tuple ((1, 2, 3)or(10, 20, 30, 40)). - It iterates through
argsand calculates the sum.
The **kwargs parameter allows you to pass a variable number of keyword arguments to a function. Inside the function, kwargs is a dictionary containing the keyword arguments passed to the function, where keys are the argument names and values are their corresponding values.
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Example usage
display_info(name="Alice", age=30, city="New York")In this example:
display_infoaccepts any number of keyword arguments (**kwargs).- Inside the function,
kwargsis a dictionary ({"name": "Alice", "age": 30, "city": "New York"}). - It iterates through
kwargsand prints each key-value pair.
You can use *args and **kwargs together in a function to handle both positional and keyword arguments simultaneously.
def process_data(*args, **kwargs):
print("Positional arguments (*args):")
for arg in args:
print(arg)
print("\nKeyword arguments (**kwargs):")
for key, value in kwargs.items():
print(f"{key}: {value}")
# Example usage
process_data(1, 2, 3, name="Alice", age=30, city="New York")In this example:
process_dataaccepts both positional arguments (*args) and keyword arguments (**kwargs).- It prints the positional arguments and then the keyword arguments.
Decorators often use *args and **kwargs to wrap and modify functions without knowing the specific arguments of the function being decorated.
def log_arguments(func):
def wrapper(*args, **kwargs):
print(f"Arguments passed to {func.__name__}:")
if args:
print("Positional arguments:")
for arg in args:
print(arg)
if kwargs:
print("Keyword arguments:")
for key, value in kwargs.items():
print(f"{key}: {value}")
return func(*args, **kwargs)
return wrapper
# Example usage of decorator with *args and **kwargs
@log_arguments
def calculate_total(*args, discount_rate=0, **kwargs):
total = sum(args)
for key, value in kwargs.items():
if key.startswith('extra_'):
total += value
return total - (total * discount_rate)
# Example call
print(calculate_total(100, 50, 75, discount_rate=0.1, extra_shipping=10, extra_handling=5))In this decorator example:
log_argumentsdecoratescalculate_total.wrapperinlog_argumentsprints all positional and keyword arguments passed tocalculate_total.calculate_totalcomputes a total based on positional arguments and keyword arguments (discount_rateand anyextra_*kwargs).
Go Back