*args and **kwargs
Introduction to Flexible Arguments
In Python, *args
and **kwargs
are powerful tools that allow functions to accept a variable number of arguments dynamically.
*args: Variable Positional Arguments
Basic Concept
*args
enables a function to accept any number of positional arguments:
def sum_numbers(*args):
total = 0
for num in args:
total += num
return total
print(sum_numbers(1, 2, 3, 4, 5)) ## Output: 15
print(sum_numbers(10, 20)) ## Output: 30
Unpacking Arguments
*args
can also be used to unpack lists or tuples:
def display_info(*args):
for arg in args:
print(arg)
numbers = [1, 2, 3]
display_info(*numbers)
**kwargs: Variable Keyword Arguments
Basic Concept
**kwargs
allows functions to accept arbitrary keyword arguments:
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_details(name="Alice", age=30, city="New York")
Combining *args and **kwargs
Advanced Function Signatures
You can combine both in a single function:
def flexible_function(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
flexible_function(1, 2, 3, name="LabEx", version=2.0)
Argument Passing Flow
graph TD
A[Function Call] --> B{Argument Type}
B --> |*args| C[Positional Arguments]
B --> |**kwargs| D[Keyword Arguments]
C --> E[Packed into Tuple]
D --> F[Packed into Dictionary]
Use Cases and Best Practices
Common Scenarios
Scenario |
Use of *args/*kwargs |
Wrapper Functions |
Preserve original function signature |
Inheritance |
Extend parent class methods |
Flexible API Design |
Create adaptable function interfaces |
Tips
- Use meaningful parameter names
- Document the expected argument types
- Validate input when necessary
- Be cautious with excessive flexibility
Advanced Example: Decorator with Flexible Arguments
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def complex_calculation(x, y, z=0):
return x + y + z
result = complex_calculation(10, 20, z=5)
By mastering *args
and **kwargs
, you'll unlock powerful techniques for creating flexible and dynamic functions in Python, enhancing your programming skills in LabEx and beyond.