side effects on *some* default parameters

Joe Grossberg jgrossberg at matrixgroup.net
Wed Feb 12 16:21:57 EST 2003


I was tripped up by this quirk of Python, and I was wondering if you 
guys could provide some insight.

>>> def sideEffect(aList=[], aStr='foo'):

...     aList.append(aStr)

...     aStr='bar'

...     print "aList is %s ... aStr is %s" % (aList, aStr)

... 

>>> sideEffect()

aList is ['foo'] ... aStr is bar

>>> sideEffect()

aList is ['foo', 'foo'] ... aStr is bar

>>> sideEffect()

aList is ['foo', 'foo', 'foo'] ... aStr is bar

Why does this happen? Specifically: when I call this function, how come 
aStr is reset to 'foo', but aList never reverts to an empty list?

Thanks for your insights,
Joe

-- 
----------------------------------------------------------
Joe Grossberg :: Programmer :: jgrossberg at matrixgroup.net
http://www.matrixmaxx.net/ :: Custom Web Solutions and 
Web-Based Association Management Software.







More information about the Python-list mailing list