Skip to content

Instantly share code, notes, and snippets.

@koitsu
Created September 23, 2018 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koitsu/292bc200dc46178cb7b7dc7948a71fbe to your computer and use it in GitHub Desktop.
Save koitsu/292bc200dc46178cb7b7dc7948a71fbe to your computer and use it in GitHub Desktop.
The coiler strikes again
#!/usr/bin/env python2.7
def test(x=[]):
x.append(2)
return x
print (test()) # returns [2]
print (test()) # returns [2, 2]
print (test()) # returns [2, 2, 2]
# The reason, emphasis mine:
#
# https://docs.python.org/2.0/ref/function.html
#
# ***Default parameter values are evaluated when the function definition is executed.
# This means that the expression is evaluated once, when the function is defined, and
# that that same ``pre-computed'' value is used for each call.*** This is especially
# important to understand when a default parameter is a mutable object, such as a
# list or a dictionary: if the function modifies the object (e.g. by appending an
# item to a list), the default value is in effect modified. ***This is generally not
# what was intended.*** A way around this is to use None as the default, and
# explicitly test for it in the body of the function ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment