Practical Examples of *args and **kwargs
Variadic Function for Arithmetic Operations
Let's create a function that can perform various arithmetic operations on any number of arguments.
def arithmetic_operations(*args, operator='+'):
result = args[0]
for i in range(1, len(args)):
if operator == '+':
result += args[i]
elif operator == '-':
result -= args[i]
elif operator == '*':
result *= args[i]
elif operator == '/':
result /= args[i]
return result
print(arithmetic_operations(1, 2, 3, 4, operator='+')) ## Output: 10
print(arithmetic_operations(10, 3, 2, operator='-')) ## Output: 5
print(arithmetic_operations(2, 3, 4, operator='*')) ## Output: 24
print(arithmetic_operations(20, 4, operator='/')) ## Output: 5.0
In this example, the arithmetic_operations()
function can accept any number of arguments using *args
, and the desired arithmetic operation is specified using the operator
keyword argument.
Suppose you want to create a function that collects an arbitrary number of user inputs and stores them in a list.
def collect_inputs(*args):
user_inputs = []
for arg in args:
user_input = input(f"Enter {arg}: ")
user_inputs.append(user_input)
return user_inputs
names = collect_inputs("name", "age", "city")
print(names)
## Output:
## Enter name: LabEx
## Enter age: 30
## Enter city: New York
## ['LabEx', '30', 'New York']
In this example, the collect_inputs()
function uses *args
to accept an arbitrary number of prompts, and then collects the user's responses and stores them in a list.
Logging Function with **kwargs
Imagine you want to create a logging function that can log messages with different levels (e.g., debug, info, warning, error) and include additional metadata.
def log_message(**kwargs):
log_level = kwargs.get('level', 'info')
message = kwargs['message']
metadata = kwargs.get('metadata', {})
print(f"[{log_level.upper()}] {message}")
for key, value in metadata.items():
print(f" {key}: {value}")
log_message(level='debug', message='This is a debug message')
## Output:
## [DEBUG] This is a debug message
log_message(level='warning', message='Something unusual happened', metadata={'user': 'LabEx', 'timestamp': '2023-04-18 12:34:56'})
## Output:
## [WARNING] Something unusual happened
## user: LabEx
## timestamp: 2023-04-18 12:34:56
In this example, the log_message()
function uses **kwargs
to accept an arbitrary number of keyword arguments, including the log level, message, and optional metadata.