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?

Community
  • 1
  • 1
Necronet
  • 6,704
  • 9
  • 49
  • 89
  • It's a special thing about default parameters; see http://effbot.org/zone/default-values.htm – Anton Kovalenko Jan 26 '13 at 16:31
  • 2
    Welcome to the Mutable Default Argument trap. You've just been burned! http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – Mark Amery Jan 26 '13 at 16:32
  • Essentially: the expression that you pass as a default argument to a function in Python is evaluated at the time of defining the function, and then the resulting object - which may be mutable - is used as the default argument. This is surprising to many people who instead assume - fairly naturally, but wrongly - that the expression will be evaluated every time the function is called. – Mark Amery Jan 26 '13 at 16:35
  • This was the fastest response I haver gotten in stackoverflow thanks – Necronet Jan 26 '13 at 16:36

0 Answers0