Learning Python – Setting Default Parameters in Functions

Default parameters are a powerful feature in Python functions that allow parameters to use predefined default values when no value is passed during the call.

1. Basic Syntax

def function_name(parameter_name=default_value):    # function body

2. Basic Usage Examples

1. Simple Default Parameter

def greet(name, message="Hello"):    print(f"{message}, {name}!")
greet("Alice")  # Output: Hello, Alice!
greet("Bob", "Hi")  # Output: Hi, Bob!

2. Multiple Default Parameters

def register(name, age, country="China", city="Beijing"):    print(f"{name}, {age} years old, from {country} {city}")
register("Zhang San", 25)  # Using all default values
register("Li Si", 30, city="Shanghai")  # Overriding some default values

3. Important Characteristics of Default Parameters

1. Timing of Default Parameter Evaluation

Default parameters are evaluated at function definition time (not at call time), which can lead to a common pitfall:

def add_item(item, lst=[]):  # Default list is created at function definition    lst.append(item)    return lst
print(add_item(1))  # [1]
print(add_item(2))  # [1, 2] instead of the expected [2]

Correct Approach:

def add_item(item, lst=None):    if lst is None:  # Create a new list on each call        lst = []    lst.append(item)    return lst

2. Position of Default Parameters

Default parameters must be placed after non-default parameters:

# Correct
def func(a, b=1, c=2):    pass
# Incorrect
# def func(a=1, b, c):#     pass

3. Immutable Objects as Default Values are Safer

def log(message, timestamp=None):  # Use None instead of mutable objects    if timestamp is None:        timestamp = datetime.now()    print(f"[{timestamp}] {message}")

4. Advanced Usage of Default Parameters

1. Using Immutable Default Values

def calculate(a, b, precision=2):    """Calculate a/b, keeping a specified number of decimal places"""    return round(a / b, precision)
print(calculate(10, 3))  # 3.33
print(calculate(10, 3, 4))  # 3.3333

2. Default Parameters with Other Parameter Types

def draw_shape(x, y, shape="circle", *, color="black", fill=True):    """Draw a shape, shape must be a positional parameter, color and fill must be keyword parameters"""    print(f"Drawing a {color} {shape} at ({x},{y}) {'filled' if fill else 'hollow'}")
draw_shape(10, 20)  # Using all default values
draw_shape(30, 40, "square", color="blue")  # Partially overriding

3. Default Parameters with Type Annotations

from typing import Optional
def send_email(    to: str,    subject: str,    body: Optional[str] = None,    cc: list[str] = None,    bcc: list[str] = None) -> bool:    """Send an email with type-annotated default parameters"""    if body is None:        body = "No content"    if cc is None:        cc = []    if bcc is None:        bcc = []    # Sending logic...    return True

5. Best Practices

1. Use None as a Mutable Default Value: Avoid issues with shared mutable objects

2. Place the Most Likely to Change Parameters Last: Easier to override default values

3. Keep Default Values Simple: Avoid using complex expressions

4. Document Default Values:

def resize(image, width=800, height=600):    """Resize an image
    Parameters:        image: The image to resize        width: Target width (default 800)        height: Target height (default 600)    """    pass

5. Avoid Using Mutable Objects as Default Values: Such as lists, dictionaries, etc.

6. Default Parameters vs Keyword Parameters

Feature Default Parameters Keyword Parameters
Definition Location At function definition time At function call time
Purpose Provide default values for parameters Explicitly specify parameter values
Syntax <span>def func(param=value)</span> <span>func(param=value)</span>
Mutable Object Pitfall Yes No
Use Cases Optional parameters Improve readability/skip certain parameters

Default parameters are a very important feature in Python function design, and their proper use can:

  • Simplify function calls

  • Provide a more flexible interface

  • Extend function capabilities in a backward-compatible way

Remember the core principle of default parameters: Default values are evaluated once at function definition time, which is key to understanding the behavior of default parameters.

Leave a Comment