How do you define optional and default arguments in a Python function? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you define optional and default arguments in a Python function?

message-square
0

Assign a fallback value directly in the function signature (def greet(name: str, greeting: str = "Hello") -> str:) to make a parameter optional with a default value, placing all default parameters after required positional parameters and always using None (never a mutable [] or {}) when a parameter needs a fresh default container per call.

Basic Example

# 1. Recommended: Required arguments first, followed by optional arguments with defaults
def format_price(amount: float, currency: str = "USD", include_symbol: bool = True) -> str:
    prefix = "$" if (include_symbol and currency == "USD") else f"{currency} "
    return f"{prefix}{amount:,.2f}"

print(format_price(49.9))                         # Output: $49.90
print(format_price(49.9, "EUR", False))           # Output: EUR 49.90
print(format_price(49.9, include_symbol=False))   # Output: USD 49.90

# 2. Recommended pattern for mutable default arguments (lists, dicts, sets):
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
    if tags is None:
        tags = []
    tags.append(tag)
    return tags

print(add_tag("python"))  # Output: ['python']
print(add_tag("pandas"))  # Output: ['pandas'] (fresh list every call!)

Key Details & Edge Cases

  • Never use mutable objects ([], {}, set()) as default values:
    • Python evaluates default parameter expressions once at function definition time (def), not on each function call, storing them in func.__defaults__. Defining def add_item(x, items=[]): causes every call without items to mutate and share the exact same list object across calls. Always default to None (items: list | None = None) and instantiate a fresh container inside the function body.
  • Parameter ordering rules (SyntaxError if violated):
    • Every parameter with a default value (b=2) must appear after all non-default parameters (def fn(a, b=2):, never def fn(a=1, b):).
    • When mixing positional-only (/), standard, *args, keyword-only (*), and **kwargs, follow Python’s strict signature order: def fn(pos_only, /, standard, standard_opt=1, *args, kw_only, kw_only_opt=2, **kwargs):
  • Enforcing keyword-only optional flags with * (def connect(host, *, timeout=5.0, retry=True):):
    • Placing a bare * before optional boolean or numeric flags prevents callers from passing confusing positional booleans like connect("db.local", 5.0, True), requiring explicit keyword arguments (connect("db.local", timeout=5.0)) while keeping the parameters optional.
  • Distinguishing “argument omitted” from “None explicitly passed” (sentinel object pattern):
    • When None itself is a valid argument value (for example, updating a database field to NULL vs. leaving it unchanged), create a private module-level sentinel object instead of defaulting to None:
      _UNSET = object()
      
      def update_user(user_id: int, bio: str | None | object = _UNSET) -> None:
          if bio is not _UNSET:
              print(f"Updating bio to: {bio!r}")
      
  • Default expressions capture current values at def time:
    • Writing def log(msg, ts=datetime.now()): freezes ts to the exact timestamp when the module was imported. Compute dynamic defaults (datetime.now(), UUIDs, random numbers) inside the function body when param is None.

Comparison of Optional Parameter Patterns in Python

Pattern Can Caller Pass Positionally? Can Caller Pass by Keyword? Safe for Lists / Dicts / Dynamic Values? Best Used When
def fn(a, opt="default"): (Recommended) Yes Yes Only for immutable constants (str, int, bool, None) Standard optional parameters with static, immutable defaults.
def fn(a, items: list | None = None): (Recommended for mutables) Yes Yes Yes (allocate items = [] inside body) Optional collections (list, dict, set) or runtime-computed defaults (datetime.now()).
def fn(a, *, flag=False, retries=3): No (keyword-only after *) Yes With immutable defaults or None guard Public APIs with multiple optional flags where positional calls hurt readability.
def fn(a, opt=_UNSET): Yes Yes Yes Patch/update functions that must distinguish omitted arguments from an explicit None.