Function Parameters in Python
Understanding how to define and use function parameters effectively is crucial for writing clean, flexible, and reusable data science code. In 2026, modern Python function parameter patterns help you create more maintainable and user-friendly functions.
TL;DR — Key Parameter Types
- Positional parameters – Required, order matters
- Default parameters – Optional with sensible defaults
- Keyword-only parameters – Force usage by name
- *args and **kwargs – For flexible arguments
1. Modern Function Parameters Example
from typing import List, Optional, Dict, Any
from datetime import datetime
def analyze_sales_data(
transactions: List[Dict[str, Any]],
min_amount: float = 0.0, # Default parameter
region: Optional[str] = None, # Optional parameter
*,
include_outliers: bool = True, # Keyword-only parameter
date_range: Optional[tuple] = None # Keyword-only
) -> Dict[str, float]:
"""
Analyze sales data with flexible parameters.
Args:
transactions: List of transaction dictionaries
min_amount: Minimum amount to include (default: 0.0)
region: Filter by specific region (optional)
include_outliers: Whether to include outlier values
date_range: Optional (start_date, end_date) tuple
Returns:
Dictionary with summary statistics
"""
# Filter logic here
filtered = [t for t in transactions if t.get("amount", 0) >= min_amount]
if region:
filtered = [t for t in filtered if t.get("region") == region]
if date_range:
start, end = date_range
filtered = [t for t in filtered if start <= t.get("date") <= end]
amounts = [t["amount"] for t in filtered]
return {
"total_sales": sum(amounts),
"average_sale": sum(amounts) / len(amounts) if amounts else 0,
"transaction_count": len(amounts),
"max_sale": max(amounts) if amounts else 0
}
2. Best Practices for Function Parameters in Data Science 2026
- Use type hints for all parameters and return values
- Provide sensible default values for optional parameters
- Use keyword-only parameters (after
*) for important flags and options - Avoid using mutable defaults (like lists or dicts) — use
Noneinstead - Keep the number of parameters reasonable (ideally ≤ 5–6)
- Use
**kwargssparingly and only when truly needed for flexibility
3. Common Data Science Function Pattern
def preprocess_data(
df,
target_column: str,
*,
drop_na: bool = True,
scale_features: bool = False,
test_size: float = 0.2
):
"""Clean and prepare data for modeling."""
if drop_na:
df = df.dropna()
# Further preprocessing logic...
return df
Kinds of Parameters
Python parameters can be positional, keyword, have defaults, or collect extras with *args and **kwargs. A bare * in the signature makes the following parameters keyword-only, which prevents confusing calls like f(df, 3, True).
Defaults should be immutable values such as None, numbers or strings. A mutable default like a list is created once and shared between calls, which causes hard-to-find bugs.
Worked Example: Keyword-Only Options
A summary function uses a required positional argument and keyword-only options.
import pandas as pd
def summarize(df, *, column, decimals=2, include=None):
stats = ["mean", "min", "max"] if include is None else include
return df[column].agg(stats).round(decimals)
df = pd.DataFrame({"sales": [10.123, 20.456, 30.789]})
print(summarize(df, column="sales"))
print(summarize(df, column="sales", decimals=0, include=["sum"]))
try:
summarize(df, "sales")
except TypeError as err:
print("TypeError:", err)
Because column is keyword-only, the positional call fails with a TypeError instead of silently mixing up arguments. include=None avoids a shared mutable default list.
Practical Tips
Parameter order matters for readability. Put the main data first, followed by the most important options, and make rarely used options keyword-only. This lets typical calls stay short while unusual settings remain explicit.
Type hints on parameters, such as column: str or decimals: int = 2, help editors catch mistakes and make the expected input obvious to anyone reading the code.
When you rename a parameter in shared code, consider accepting the old name for a while and warning callers. This avoids breaking notebooks and scripts written by other people who depend on your function.
Common Mistakes
- Using a mutable list or dict as a default value.
- Long lists of positional arguments that are easy to swap.
- Hiding required options inside **kwargs.
- Changing parameter order and breaking existing callers.
Quick Summary
- Use keyword-only parameters for options.
- Use None as a default for mutable values.
- Keep parameter lists short.
- Reserve *args and **kwargs for real flexibility.
Conclusion
Well-designed function parameters make your data science code more flexible, readable, and maintainable. In 2026, the standard is to use type hints, sensible defaults, and keyword-only parameters for important options. Following these practices will help you write professional, reusable functions that other data scientists can easily understand and use.
Next steps:
- Review your existing data science functions and improve them by adding type hints, better defaults, and keyword-only parameters where appropriate