Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)
Mutable vs Immutable data types:
In Simple Words:
- Immutable:
int,float,str,tuple,frozenset,bytes. Modifying one creates a brand-new object in memory. - Mutable:
list,dict,set. Elements can be modified in-place without changing the object's memory address pointer.
python
# Dangerous default mutable argument bug:
def append_item(val, target=[]): # target is evaluated ONCE at definition time!
target.append(val)
return target
print(append_item(1)) # [1]
print(append_item(2)) # [1, 2] -- UNEXPECTED!
# Safe idiom:
def safe_append(val, target=None):
if target is None: target = []
target.append(val)
return target