Flexible Argument Patterns
Variable-Length Arguments (*args)
The *args
syntax allows functions to accept any number of positional arguments.
def sum_numbers(*args):
total = sum(args)
return total
print(sum_numbers(1, 2, 3, 4, 5)) ## Output: 15
print(sum_numbers(10, 20)) ## Output: 30
Keyword Variable-Length Arguments (**kwargs)
The **kwargs
syntax enables functions to accept an arbitrary number of keyword arguments.
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")
Combining *args and **kwargs
You can use both *args
and **kwargs
in the same function for maximum flexibility.
def advanced_function(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
advanced_function(1, 2, 3, x=10, y=20)
Argument Unpacking
Unpacking Lists and Tuples
def multiply(a, b, c):
return a * b * c
numbers = [2, 3, 4]
print(multiply(*numbers)) ## Equivalent to multiply(2, 3, 4)
Unpacking Dictionaries
def create_profile(name, age, city):
return f"{name} is {age} years old from {city}"
person_info = {'name': 'Bob', 'age': 25, 'city': 'London'}
print(create_profile(**person_info))
Function Argument Flow
graph TD
A[Function Call] --> B{Argument Types}
B --> |Positional| C[*args]
B --> |Keyword| D[**kwargs]
C --> E[Tuple of Arguments]
D --> F[Dictionary of Arguments]
Practical Use Cases
Scenario |
Technique |
Example |
Unknown number of arguments |
*args |
Calculating sum |
Dynamic keyword arguments |
**kwargs |
Logging function |
Flexible function signatures |
Combining *args, **kwargs |
Configuration handlers |
Advanced Argument Patterns
Forcing Keyword Arguments
def strict_function(*, keyword1, keyword2):
print(keyword1, keyword2)
## This will work
strict_function(keyword1="LabEx", keyword2="Python")
## This will raise an error
## strict_function("LabEx", "Python")
Best Practices
- Use
*args
and **kwargs
sparingly
- Document the expected argument structure
- Maintain readability and clarity
- Consider type hints for better code understanding
By mastering these flexible argument patterns, you'll write more dynamic and adaptable Python functions in your LabEx projects.