| theme | default | |
|---|---|---|
| background | https://source.unsplash.com/collection/94734566/1920x1080 | |
| class | text-center | |
| highlighter | shiki | |
| lineNumbers | true | |
| drawings |
|
def add_item(item, my_list=[]):
my_list.append(item)
return my_list
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] 😱Wait, where did 1 come from?
- Default parameters are evaluated only once at function definition time
- The empty list is created when the function is defined
- The same list object is reused for every call where a list isn't provided
- Modifications persist between function calls
When Python loads the function definition:
def add_item(item, my_list=[]):
...- It creates an empty list object in memory
- It binds the parameter
my_listto reference this object - This happens just once when the module loads
- All calls to
add_item()without a second argument will use the same list object
def add_item(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list
print(add_item(1)) # [1]
print(add_item(2)) # [2] ✅Noneis immutable and safe to use as a default value- A new empty list is created each time the function is called
- Each call gets its own unique list
- No more unexpected shared state between calls
Never use mutable objects as default parameters:
- ❌ Lists:
def func(param=[]) - ❌ Dictionaries:
def func(param={}) - ❌ Sets:
def func(param=set()) - ✅ Immutable types are safe:
None,0,"",(), etc.