1

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

I tried to find the answer in SO, or python but could not get a reference.

import random 

def test(headers=[('Application','Value')]):
    print headers
    headers.append(('Random',random.randint(0,100)))
    print headers


test()
test()
test()

I keep getting this output

[('Application', 'Value')]
[('Application', 'Value'), ('Random', 8)]
[('Application', 'Value'), ('Random', 8)]
[('Application', 'Value'), ('Random', 8), ('Random', 46)]
[('Application', 'Value'), ('Random', 8), ('Random', 46)]
…………

When I run this code seems that python holds the values of headers even though is a function parameter. Me comming from a Java, .NET and php still do not see the logic into this.

Can someone enlighten me?

4

0 回答 0