Default Function Parameters in Python: A "Lazy" Usage Function Parameter Defaults: Python's "Lazy" Approach for Function Arguments

In Python, function parameters can have default values assigned during definition. If a parameter is not provided when calling the function, the default value is automatically used, simplifying the process of passing repeated arguments. For basic usage, consider `greet(name="stranger")`; when `name` is not passed, the default "stranger" is used, but passing a value will override this default. Multiple default parameters must come after positional parameters; otherwise, a syntax error will occur (e.g., `def calc_area(length=5, width=3)` is valid, while `def calc_area(length=5, width)` is invalid). A common pitfall involves mutable objects like lists as default values, which can cause "reuse" of the same object instance. This means subsequent calls will retain the previous function's state (e.g., `add_item("苹果")` followed by `add_item("香蕉")` will result in `["苹果", "香蕉"]`). To avoid this, it is recommended to set the default value to `None` and create a new object within the function (e.g., `def add_item(item, items=None): items = items or []; items.append(item)`). Mastering these techniques—simplifying function calls, paying attention to parameter order, and avoiding the reuse of mutable object defaults—will make your functions more concise and reliable.

Read More