Re:Ask HN: What are your favorite examples of elegant software?
by darkfirefly on Monday May 02, 2022 @09:58PM
(#31243529)
Python's default arguments are evaluated and stored once. This can cause issues, for example the naive "default to []" program:
>>> def function(b, a=[]):
... a.append(b)
... print(a)
...
...
>>> function(1)
[1]
>>> function(2)
[1, 2]
>>> function(3, [4])
[4, 3]
>>> function(5)
[1, 2, 5]
A correct implementation would be: >>> def function2(b, a=None):
... if a is None: a = []
... a.append(b)
... print(a)
Re:Ask HN: What are your favorite examples of elegant software?
by MisterBiggs on Tuesday May 03, 2022 @12:24AM
(#31244596)
Surprised to see this works for list() as well.
>>> def func(b, a=list()):
... a.append(b)
... print(a)
...
>>> func(3)
[3]
>>> func(3)
[3, 3]
Honestly surprised this quirk hasn't bit me yet
Re:Ask HN: What are your favorite examples of elegant software?
by thrtythreeforty on Monday May 02, 2022 @10:04PM
(#31243575)
Yep and that's also the source of the footgun:
def foobar(my_list=[]): my_list.append(42)
A cursory glance suggests this function appends a number to an empty list every time it's run. But actually, the default argument is evaluated once when the function is defined, so calling this function repeatedly will continue to append to that same list.
Re:Ask HN: What are your favorite examples of elegant software?
by thatfunkymunki on Tuesday May 03, 2022 @04:27PM
(#31253154)
yeah, this has consequences for constructors too, you don't want to specify default values in the __init__ function signature because of this.
You're saying python computes an expression that's part of a default value when the code defining the function is run? I guess it makes sense now that i say it, I wouldn't have automatically assumed that. That's an interesting one to remember.