Functions are reusable blocks of code defined using the def keyword. Modern Python emphasizes type hints, explicit parameter binding rules, and clean return values.
flowchart TD
A["def func(pos_only, /, standard, *, kw_only):"]
A --> B["/ : Forces Positional-Only Parameters"]
A --> C["Standard: Positional or Keyword"]
A --> D["* : Forces Keyword-Only Parameters"]
func(key=val)).*args: Collects excess positional arguments as a tuple.**kwargs: Collects excess keyword arguments as a dictionary.from typing import List, Dict, Any, Optional
def build_api_response(
status_code: int,
message: str,
/, # Positional-only parameters before '/'
*, # Keyword-only parameters after '*'
data: Optional[Dict[str, Any]] = None,
tags: Optional[List[str]] = None
) -> Dict[str, Any]:
"""Construct a standardized JSON API response object."""
payload: Dict[str, Any] = {
"status": status_code,
"message": message,
"success": 200 <= status_code < 300,
"data": data or {},
"tags": tags or []
}
return payload
if __name__ == "__main__":
# Correct invocation (positional before '/', keyword after '*')
response = build_api_response(
200, "OK",
data={"user_id": 42},
tags=["auth", "v1"]
)
print("API Response:", response)
def func(lst=[]) retains state across calls! Use def func(lst: list | None = None): if lst is None: lst = [].-> ReturnType (or -> None if no value is returned).Write a function calculate_total(price: float, tax_rate: float = 0.05, discount: float = 0.0) -> float with complete type annotations.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With