<div dir="ltr">There are two issues** here:<br><br>(1) def foo(L=[]):<br>the [] is a single list, not a new list created every time the function is called.<br><br>(2) def foo(L=list()):<br>the list() is evaluated once when the function is declared.<br>
<br>I think (1) is easy to explain; I find (2) confusing. (**Yes, I realize that these can be considered the same issue, but I'm speaking here as a person writing python programs, not designing the language.) On the other hand, consider this code:<br>
<br> bar = 1<br> def foo(arg=bar):<br> print(arg)<br> bar = 2<br> foo()<br><br>I would be very surprised if foo() printed 2 rather than 1. The difference to my (programmer's) mind is that in this case bar looks like a simple value and list() looks like a function call. So it's not quite that simple. At least the way it works now is completely consistent and the code:<br>
<br> def foo(arg=None):<br> arg = bar if arg is None else arg<br> arg2 = list() if arg is None else arg<br><br>is unambiguous if clumsy.<br><br>Now thinking as a language designer, C# has a ?? operator where A??B is shorthand for (B if A is None else A) except you only have to write A once and A is only evaluated once. A Pythonesque version of this would be just "else":<br>
<br> def foo(arg=None, arg2=None):<br> arg = arg else bar<br> arg2 = arg2 else list()<br> <br>And I think that metaphor is easy to read. Chains of else operators can be useful:<br><br> x = f() else g() else h() else 0<br>
<br>--- Bruce<br></div>