Advanced Parameter Techniques
Keyword Arguments
Keyword arguments provide more flexibility in function calls by allowing arguments to be passed in any order:
def create_user(username, email, age=None, role='user'):
return {
'username': username,
'email': email,
'age': age,
'role': role
}
## Flexible function calls
user1 = create_user('john_doe', '[email protected]')
user2 = create_user(email='[email protected]', username='jane_doe', role='admin')
Variable-Length Arguments
*args (Positional Variable-Length Arguments)
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3, 4, 5)) ## Outputs: 15
**kwargs (Keyword Variable-Length Arguments)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")
Argument Unpacking
graph TD
A[Argument Unpacking] --> B[*args Unpacking]
A --> C[**kwargs Unpacking]
B --> D[Positional Arguments]
C --> E[Keyword Arguments]
List/Tuple Unpacking
def multiply(a, b, c):
return a * b * c
numbers = [2, 3, 4]
print(multiply(*numbers)) ## Equivalent to multiply(2, 3, 4)
Dictionary Unpacking
def create_profile(name, age, city):
return f"{name} is {age} years old from {city}"
user_data = {'name': 'Bob', 'age': 25, 'city': 'London'}
print(create_profile(**user_data))
Combining Argument Types
def complex_function(a, b, *args, option=True, **kwargs):
print(f"a: {a}, b: {b}")
print(f"Additional args: {args}")
print(f"Option: {option}")
print(f"Keyword args: {kwargs}")
complex_function(1, 2, 3, 4, option=False, x=10, y=20)
Function Annotations
Annotation Type |
Description |
Example |
Parameter Types |
Hint parameter types |
def func(x: int, y: str) |
Return Types |
Specify return type |
def func(x: int) -> str: |
Type Hinting Example
def calculate_area(length: float, width: float) -> float:
return length * width
## Provides type information without runtime enforcement
print(calculate_area(5.5, 3.2))
Decorator for Advanced Parameter Handling
def validate_parameters(func):
def wrapper(*args, **kwargs):
## Add custom parameter validation logic
return func(*args, **kwargs)
return wrapper
@validate_parameters
def process_data(data: list, multiplier: int = 2):
return [x * multiplier for x in data]
Context Managers and Parameters
class DatabaseConnection:
def __init__(self, host='localhost', port=5432):
self.host = host
self.port = port
def __enter__(self):
## Establish connection
return self
def __exit__(self, exc_type, exc_val, exc_tb):
## Close connection
Practical Considerations
- Balance between flexibility and readability
- Use type hints for better code documentation
- Be cautious with complex parameter combinations
- Prioritize code clarity
Conclusion
Advanced parameter techniques in Python offer powerful ways to create flexible and robust functions, enabling more dynamic and expressive code design.