Skip to content

Instantly share code, notes, and snippets.

@natesilva
Created December 1, 2009 18:24
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 natesilva/246507 to your computer and use it in GitHub Desktop.
Save natesilva/246507 to your computer and use it in GitHub Desktop.
# Example showing how a subtlety in the way Python handles default
# arguments can cause a bug.
class C(object):
def __init__(self, list1=[], list2=None):
# Wrong: if the list1 default argument of [] is used, that
# default will be *shared* among all instances of the class.
# If it is later modified, other instances can unexpectedly
# inherit the modifications.
self.list1 = list1
# With list2 we do things the right way
if list2 is None:
list2 = []
self.list2 = list2
c1 = C()
c1.list1.append('foo')
c1.list1.append('bar')
c1.list2.append('peachy')
c1.list2.append('keen')
c2 = C()
print c2.list1 # prints ['foo', 'bar']
print c2.list2 # prints []
c2.list1.append('baz')
print c1.list1 # prints ['foo', 'bar', 'baz']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment