I came across something today that I considered very odd.
>>> import StringIO
>>> def test(thing=StringIO.StringIO()):
... thing.write("test")
... print thing.getvalue()
...
>>> test()
test
>>> test()
testtest
>>> test()
testtesttest
>>> test()
testtesttesttest
>>> test()
testtesttesttesttest
Before today I would have read the line
def test(thing=StringIO.StringIO()):
as:
Declare a function which, whose kwargs dictionary, when called has a new
StringIO
by default as the value for the key 'thing', and add it to the current scope.
but from the example I think it's more like:
Declare a function. Construct a dictionary with a new
StringIO
in it. Assign this to the default kwargs of the function and add the function to the current scope.
Is this the correct interpretation? Are there any other gotchas to be aware of for default kwargs?