Default Parameters in Python
Introduction
In Python, functions can have parameters with default values. These are called default parameters.
Default parameters allow you to call a function without providing all arguments, making your code more flexible and concise.
Default parameters provide flexibility and simplicity in function calls.
What Are Default Parameters?
Default parameters are values assigned to function parameters that are used if no argument is provided during the function call.
They help avoid errors and reduce the need for multiple function overloads.
- Defined by assigning a value in the function signature.
- Used when the caller omits the argument.
- Must come after non-default parameters in the function definition.
Syntax and Usage
To define a default parameter, assign a value to the parameter in the function header.
When calling the function, if you omit the argument, the default value is used.
- Default parameters are defined as: def func(param=default_value):
- Non-default parameters must precede default parameters.
- You can override default values by providing arguments.
Example of Default Parameters
Here is a simple example demonstrating default parameters in Python.
Common Use Cases
Default parameters are useful when you want to provide optional functionality or sensible defaults.
They are often used in configuration settings, logging, and utility functions.
- Setting default values for optional arguments.
- Avoiding repetitive code by providing common defaults.
- Simplifying function calls for common cases.
Important Considerations
Mutable default parameters can lead to unexpected behavior.
Always use immutable types like None, numbers, or strings as default values when possible.
- Default parameter values are evaluated once at function definition time.
- Using mutable objects like lists or dictionaries as defaults can cause shared state issues.
- Use None as a default and initialize inside the function if needed.
Example of Mutable Default Parameter Pitfall
This example shows how mutable default parameters can cause bugs.
Examples
def greet(name='Guest'):
print(f'Hello, {name}!')
greet() # Output: Hello, Guest!
greet('Alice') # Output: Hello, Alice!The function greet uses a default parameter 'name' with the value 'Guest'. If no argument is passed, it greets 'Guest'.
def append_item(item, item_list=[]):
item_list.append(item)
return item_list
print(append_item(1)) # Output: [1]
print(append_item(2)) # Output: [1, 2] (unexpected)The list item_list is shared across calls because the default list is created once. This causes unexpected accumulation of items.
def append_item(item, item_list=None):
if item_list is None:
item_list = []
item_list.append(item)
return item_list
print(append_item(1)) # Output: [1]
print(append_item(2)) # Output: [2]Using None as the default and initializing inside the function avoids shared mutable default issues.
Best Practices
- Always place default parameters after non-default parameters in function definitions.
- Avoid using mutable objects as default parameter values.
- Use None as a default for mutable parameters and initialize inside the function.
- Provide meaningful default values that make sense for your function's purpose.
- Document default parameter behavior clearly in your function docstrings.
Common Mistakes
- Placing default parameters before non-default parameters, causing syntax errors.
- Using mutable objects like lists or dictionaries as default parameters leading to shared state bugs.
- Assuming default parameters are re-evaluated on each function call.
- Not overriding default parameters when needed, causing unexpected behavior.
Hands-on Exercise
Create a Function with Default Parameters
Write a Python function that calculates the power of a number with a default exponent of 2.
Expected output: Calling the function with one argument squares the number; with two arguments, it raises to the given power.
Hint: Use a default parameter for the exponent.
Fix Mutable Default Parameter Bug
Given a function that appends items to a list with a default empty list, modify it to avoid shared state issues.
Expected output: Each function call returns a list containing only the newly appended item.
Hint: Use None as the default and initialize inside the function.
Interview Questions
What happens if you use a mutable object as a default parameter in Python?
InterviewThe mutable object is created once when the function is defined, so all calls without that argument share the same object, which can lead to unexpected behavior.
Can default parameters be expressions or function calls?
InterviewDefault parameter values are evaluated once at function definition time, so expressions or function calls used as defaults are evaluated only once, not each time the function is called.
Why must default parameters come after non-default parameters in Python function definitions?
InterviewBecause Python matches positional arguments first, placing default parameters before non-default ones causes ambiguity and syntax errors.
Summary
Default parameters in Python provide a way to define functions with optional arguments.
They improve code flexibility and reduce the need for multiple function overloads.
Be cautious with mutable default parameters to avoid bugs caused by shared state.
Following best practices ensures your functions behave as expected and are easy to use.
FAQ
Can default parameters be changed after function definition?
No, default parameter values are fixed at function definition time and cannot be changed dynamically.
What is the order of evaluation for default parameters?
Default parameters are evaluated once when the function is defined, not each time the function is called.
Is it possible to have all parameters with default values?
Yes, you can define a function where all parameters have default values, making all arguments optional.
