[Tutor] functions and default argument

Prasad, Ramit ramit.prasad at jpmorgan.com
Fri Oct 21 21:40:39 CEST 2011


>The same thing occurs when you use a mutable object like a list or a 
>dict. The default value is assigned once, and once only. But notice that 
>you can modify the default value, say by appending to it:

Not sure this will work exactly the same way in other IDEs, but in mine:

>>> a = []
>>> def foo(x=a):
...     x.append(1)
...     
>>> a.append( 2 )
>>> foo()
>>> print a
[2, 1]
>>> help(foo)
Help on function foo in module __pieshell__:

foo(x=[2, 1])

>>> foo()
>>> help(foo)
Help on function foo in module __pieshell__:

foo(x=[2, 1, 1])

>>> a.append( 3 )
>>> help(foo)
Help on function foo in module __pieshell__:

foo(x=[2, 1, 1, 3])
>>> b = []
>>> foo(b)
>>> b
[1]


Notice how it is always bound to the list a, but can be "overridden".

I know this has been discussed on this list or the main list before if you take a look through the archives.
Sorry I can't remember what the thread would be like or when it was :(
http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument 


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423




This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list