I learned something very curious in a lecture recently. This:
def f(n: int, L: list=[]) -> list:
L.append(n)
return L
will produce the following in the shell:
>>> f(7)
[7]
>>> f(17)
[7, 17]
In the second command, what the coder would probably expect is[17] to be returned, not [7, 17]. That's because there includes the default parameter L which should create an empty list to append to, right?
The only important thing that Danny wanted us to learn is to NEVER USE MUTABLE OBJECTS FOR DEFAULT PARAMETERS. He then explained the reason is because L is stored as an object within f.__defaults__, and it is used at every function call. I'm still confused by this. If a default parameter is stored and used at each function call, why doesn't this happen with non-mutable objects like ints and strings? What is it about mutable objects that allow this weird behavior?
I made a second example of this function and showed it to Danny. Here it is:
def g(n:int, r:int=0) -> int:
r += n
return r
I asked Danny to explain a critical difference between functions f and g that change the behavior of the two functions. If I remember correctly, he stressed that r += n is a reassignment to an object while L.append(n) is a modification. I think all that means is that reassignments change the value that r points to, while a modification changes the properties of L. Despite thinking this way, I still don't see why a mutable object would be treated any differently when it comes to behavior around default parameters. That's as far as I managed to dig, but I can't spend too much time thinking about this.
No comments:
Post a Comment