Have you ever thought that when writing a Python function, if certain parameters are frequently used with the same value, you don’t have to type them out every time? For example, writing a function to calculate age where the default age is 18 unless the user specifies otherwise. In such cases, function parameter default values can be a lifesaver!
What are Function Parameter Default Values?¶
Function parameter default values are “backup values” assigned to parameters when defining the function. When you call the function, if the parameter isn’t explicitly provided, Python automatically uses this default value. This simplifies function calls, reduces redundant code, and is like a handy “shortcut” for lazy programmers!
Basic Usage: Adding a “Backup” to Parameters¶
A simple example: a greeting function that defaults to greeting a “stranger”:
def greet(name="stranger"):
print(f"Hello, {name}!")
# Call without passing name (uses default)
greet() # Output: Hello, stranger!
# Call with a name (overrides default)
greet("Xiaoming") # Output: Hello, Xiaoming!
Here, name="stranger" is the default value. When greet() is called, Python uses "stranger" by default; if you pass "Xiaoming", it overrides the default.
Multiple Default Parameters: Watch the Order!¶
If a function has multiple parameters with default values, the parameters with defaults must come after positional parameters (without defaults), otherwise Python will throw an error. For example:
# Correct Example: Default parameters at the end
def calc_area(length=5, width=3):
return length * width
print(calc_area()) # Output: 15 (5*3)
print(calc_area(4)) # Output: 12 (4*3)
print(calc_area(4, 6)) # Output: 24 (4*6)
# Error Example: Default parameter first (syntax error)
def calc_area(length=5, width): # SyntaxError!
return length * width
The reason is that Python requires positional parameters without defaults to be defined first, followed by parameters with defaults. Otherwise, Python can’t determine parameter correspondence.
Common Pitfall: “Reused” Default Values¶
A common gotcha: if the default value is a mutable object (e.g., list, dictionary), it “remembers” the result of the last call, leading to unexpected behavior.
Error Example (List Default):¶
def add_item(item, list_items=[]):
list_items.append(item)
return list_items
# First call
print(add_item("apple")) # Output: ['apple']
# Second call (no new list passed)
print(add_item("banana")) # Output: ['apple', 'banana']
You might expect the second call to only add “banana”, but it returns ['apple', 'banana']. This is because the default [] is the same list object created when the function is defined and reused in every call!
Correct Solution: Initialize with None¶
To avoid this, set the default value to None and create a new mutable object inside the function:
def add_item(item, list_items=None):
if list_items is None: # If no new list is passed, create an empty list
list_items = []
list_items.append(item)
return list_items
# First call
print(add_item("apple")) # Output: ['apple']
# Second call (no new list passed, uses fresh empty list)
print(add_item("banana")) # Output: ['banana']
Now each call uses a new list, preventing the default value from being “reused”.
Summary: “Lazy” Tips for Default Parameters¶
- Simplify Calls: Set defaults for frequently used parameters to avoid repeated input.
- Order Matters: Place parameters with defaults after positional parameters.
- Beware of Mutable Defaults: For lists/dictionaries, use
Noneto initialize and create new objects inside the function.
Master these tricks, and your functions will be cleaner, more reliable, and “lazy” while still producing high-quality code!