Function Parameters in Python

Data Science Tool Box Mar 18, 2026

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 None instead
  • Keep the number of parameters reasonable (ideally ≤ 5–6)
  • Use **kwargs sparingly 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

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices