Skip to content

Instantly share code, notes, and snippets.

@rongpenl
Created May 23, 2023 05:55
Show Gist options
  • Save rongpenl/d69a29930a8155de4fa743edaa8151a8 to your computer and use it in GitHub Desktop.
Save rongpenl/d69a29930a8155de4fa743edaa8151a8 to your computer and use it in GitHub Desktop.
Don't pass mutable object to function as default value
"""
hollyandprosper.com
YouTube Channel: https://www.youtube.com/@hollyandprosper
Link to the original YouTube Short: https://youtu.be/lATMth5wb1E
"""
# wrong way
def add_tourist(tourist, tourist_list=[]):
tourist_list.append(tourist)
return tourist_list
# inspect
print(add_tourist("Andy"))
import inspect
sig = inspect.signature(add_tourist)
params = sig.parameters
for name, param in params.items():
if param.default is not param.empty:
print(f"{name}: {param.default}")
# correct way
def add_tourist(tourist, tourist_list=None):
if tourist_list is None:
tourist_list = []
tourist_list.append(tourist)
return tourist_list
print(add_tourist("Andy"))
print(add_tourist("Bob"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment