Skip to content

Instantly share code, notes, and snippets.

@henryroe
Created October 3, 2014 00:48
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 henryroe/b4fb4a99d96f69e27658 to your computer and use it in GitHub Desktop.
Save henryroe/b4fb4a99d96f69e27658 to your computer and use it in GitHub Desktop.
Example of why you shouldn't use a mutable as a default parameter in python
class BadIdea():
def __init__(self, history=[]):
self.history = history
def get_history(self):
return self.history
def append_history(self, input):
self.history.append(input)
a = BadIdea()
b = BadIdea()
print "a.history = {}".format(a.get_history())
print "b.history = {}".format(b.get_history())
# output:
# a.history = []
# b.history = []
print "\n\na.append_history('abc')"
a.append_history('abc')
print "a.history = {}".format(a.get_history())
print "b.history = {}".format(b.get_history())
# output:
# a.append_history('abc')
# a.history = ['abc']
# b.history = ['abc']
print "\n\nb.append_history('123')"
b.append_history('123')
print "a.history = {}".format(a.get_history())
print "b.history = {}".format(b.get_history())
# output:
# b.append_history('123')
# a.history = ['abc', '123']
# b.history = ['abc', '123']
print "\n\n\n"
class BetterIdea():
def __init__(self, history=None):
if history is None:
self.history = []
else:
self.history = history
def get_history(self):
return self.history
def append_history(self, input):
self.history.append(input)
a = BetterIdea()
b = BetterIdea()
print "a.history = {}".format(a.get_history())
print "b.history = {}".format(b.get_history())
# output:
# a.history = []
# b.history = []
print "\n\na.append_history('abc')"
a.append_history('abc')
print "a.history = {}".format(a.get_history())
print "b.history = {}".format(b.get_history())
# output:
# a.append_history('abc')
# a.history = ['abc']
# b.history = []
print "\n\nb.append_history('123')"
b.append_history('123')
print "a.history = {}".format(a.get_history())
print "b.history = {}".format(b.get_history())
# output:
# b.append_history('123')
# a.history = ['abc']
# b.history = ['123']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment