functions, optional parameters

Rustom Mody rustompmody at gmail.com
Fri May 8 08:09:42 EDT 2015


On Friday, May 8, 2015 at 5:30:15 PM UTC+5:30, Michael Welle wrote:
> Hello,
> 
> assume the following function definition:
> 
> def bar(foo = []):
>     print("foo: %s" % foo)
>     foo.append("foo")
> 
> It doesn't work like one would expect (or as I would expect ;-)). As I
> understand it the assignment of the empty list to the optional parameter
> foo take place when the function object is created, not when it is
> called. I think from the perspective of a user this is very strange.
> Anyways, what would be a good idiom to get the desired behaviour?

A standard gotcha of python.

Short version: Dont default optionals to mutable data structures

Longer: See http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments

[Or just run a search for "python mutable default" ]




More information about the Python-list mailing list