Flexible Function Signatures
Variable-Length Arguments
*args: Positional Variable Arguments
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3)) ## 6
print(sum_numbers(10, 20, 30, 40)) ## 100
**kwargs: Keyword Variable Arguments
def print_user_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_user_info(name="Alice", age=30, city="New York")
Combined Argument Techniques
def advanced_function(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
advanced_function(1, 2, 3, name="John", role="admin")
Function Signature Patterns
flowchart TD
A[Function Signatures] --> B[Fixed Arguments]
A --> C[*args]
A --> D[**kwargs]
A --> E[Combination Patterns]
B --> F[Mandatory Parameters]
C --> G[Variable Positional]
D --> H[Variable Keyword]
E --> I[Flexible Calling]
Argument Unpacking
Positional Argument Unpacking
def multiply(x, y, z):
return x * y * z
numbers = [2, 3, 4]
print(multiply(*numbers)) ## 24
Keyword Argument Unpacking
def create_profile(name, age, city):
return f"{name} is {age} years old from {city}"
user_data = {"name": "Sarah", "age": 28, "city": "London"}
print(create_profile(**user_data))
Advanced Signature Techniques
Technique |
Description |
Example |
Positional-Only |
Arguments can't be passed as keywords |
def func(x, y, /) |
Keyword-Only |
Arguments must be passed as keywords |
def func(*, x, y) |
Mixed Signatures |
Combine different argument types |
def func(x, y, /*, z) |
Practical Example
def flexible_data_processor(
*raw_data, ## Variable positional arguments
transform=None, ## Optional transformation
**metadata ## Variable keyword arguments
):
processed_data = list(raw_data)
if transform:
processed_data = [transform(item) for item in processed_data]
return {
"data": processed_data,
"metadata": metadata
}
## Multiple calling styles
result1 = flexible_data_processor(1, 2, 3)
result2 = flexible_data_processor(
1, 2, 3,
transform=lambda x: x*2,
source="manual_input"
)
LabEx Recommendation
Master flexible function signatures to write more adaptable and reusable Python code.
Best Practices
- Use
*args
for variable positional arguments
- Use
**kwargs
for variable keyword arguments
- Combine techniques for maximum flexibility
- Be mindful of readability and complexity