Skip to content

Instantly share code, notes, and snippets.

@townie
Created July 23, 2018 22:00
Show Gist options
  • Save townie/95f37145ca66ef0ad62cbd11c4453495 to your computer and use it in GitHub Desktop.
Save townie/95f37145ca66ef0ad62cbd11c4453495 to your computer and use it in GitHub Desktop.
# WHY parameters that are mutable in params
def foo_str(l='A', a=None):
print('BEFORE')
print(l)
print("AFTER")
l + a
print(l)
def foo_list(l=[], a=None):
print('BEFORE')
print(l)
print("AFTER")
l.append(a)
print(l)
CONST_LIST = []
def foo_list_const(l=CONST_LIST, a=None):
print('BEFORE')
print(l)
print("AFTER")
l.append(a)
print(l)
def foo_list_good(l=None, a=None):
if l is None:
l = []
print('BEFORE')
print(l)
print("AFTER")
l.append(a)
print(l)
foo_str(a='B')
foo_str(a='a')
print("TEST WITH [] in PARAMS")
print("FIRST \n")
foo_list(a='haha')
print("Second \n")
foo_list(a='haha2')
print("TEST WITH [] as CONST")
print("FIRST \n")
foo_list_const(a='haha')
print("Second \n")
foo_list_const(a='haha2')
print("TEST WITH NONE THEN init inside")
print("FIRST \n")
foo_list_good(a='haha')
print("Second \n")
foo_list_good(a='haha2')
# >> OUTPUT
# BEFORE
# A
# AFTER
# A
# BEFORE
# A
# AFTER
# A
# TEST WITH [] in PARAMS
# FIRST
# BEFORE
# []
# AFTER
# ['haha']
# Second
# BEFORE
# ['haha']
# AFTER
# ['haha', 'haha2']
# TEST WITH [] as CONST
# FIRST
# BEFORE
# []
# AFTER
# ['haha']
# Second
# BEFORE
# ['haha']
# AFTER
# ['haha', 'haha2']
# TEST WITH NONE THEN init inside
# FIRST
# BEFORE
# []
# AFTER
# ['haha']
# Second
# BEFORE
# []
# AFTER
# ['haha2']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment