Created
May 23, 2023 05:55
-
-
Save rongpenl/d69a29930a8155de4fa743edaa8151a8 to your computer and use it in GitHub Desktop.
Don't pass mutable object to function as default value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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