all Python 3Functionsterm
Default parameters
parameters
Parameters may have a default value. A mutable object as a default is a trap! Use the None pattern instead.
Syntax
def f(x, y=10): ...
A default value is evaluated once, when the function is defined — not on every call. So the same list or dict survives between calls and accumulates changes; the None pattern (y=None, then if y is None: y = [] inside) builds a fresh object each time.
Examples
def greet(name='World'):
return f'Hello, {name}!'
print(greet()) # → Hello, World!
print(greet('Alice')) # → Hello, Alice!
# Ловушка: изменяемый default
def bad(lst=[]):
lst.append(1)
return lst
print(bad()) # → [1]
print(bad()) # → [1, 1] — тот же список!
# None-паттерн (правильно)
def good(lst=None):
if lst is None:
lst = []
lst.append(1)
return lst
print(good()) # → [1]
print(good()) # → [1]
def connect(host='localhost', port=5432):
return f'{host}:{port}'
print(connect()) # → localhost:5432
print(connect(port=3306)) # → localhost:3306
See also
Open in the full glossarydocs.python.orgReport an inaccuracy