51 points · by thunderbong · 2y ago · 99 comments
The more unintuitive example of this to me is in function defaults, because those feel more like part of the function signature--i.e. I'd expect them to be assigned at function call time. But apparently, function defaults get called once when the function is defined.
>>> def grow(items=[0]):
... items.append(items[-1] + 1)
... return items
...
>>> grow()
[0, 1]
>>> grow()
[0, 1, 2]
>>> grow()
[0, 1, 2, 3]In more sane languages, the expression [] means give me an empty list value, nothing more and nothing less. So then whatever the syntax for [[]]*4 is in such sane languages, it gives you four empty list values. If you want something more imperative, you can get it, but it most cases, you don't want or even need such things.
Python makes no distinction, at a level able to be visualized by the user, between immutable and mutable data. There are a lot of bizarre situations in Python that will bite you like this. And in most cases, it's strange that such behaviors were chosen as the deault.
I don't buy this. Either the syntax to give you four empty list values is some kind of comprehension, which Python has and does exactly what you like, or it must have lazy evaluation somehow. Otherwise, how can the language know you don't want to copy the existing reference but create a new empty list? If [[]]*4 were to create new list on the fly, then `[print('hello')]*4` would have to print hello 4 times, i.e., the print statement is lazily executed, which does not fit into Python at all.
> In more sane languages, the expression [] means give me an empty list value, nothing more and nothing less
What is a “list value”? It’s either a pointer to some other space where the lists values are stored, or it’s the values stored themselves. If you say it’s the second (I can’t think of any language that does), then `a = […]; b = a` is an expensive copy by value assignment. Is that worth that trade off to get less surprising results in the articles case? I’m not saying the answer is “obviously no”, but it definitely isn’t “obviously yes”.
In Swift collections are value types, so b = a conceptually is a copy. It’s not expensive, though, because Swift does copy-on-write.
You pay for that by a combination of having more expensive collection updates (they, at least conceptually, have to check whether to make that copy) and a more complex compiler (it tries to avoid having to actually do those checks at runtime)
var a: [Int]=[]
var b = [a,a,a,a]
b[0].append(1)
print(b)
will produce [[1],[],[],[]]The interpreter is slightly more clever and instead implements this as a copy-on-writr mechanism, but that's just an implementation detail .
Actually, if you really want to have re-evaluting (sub)expressions, then Python does give you an option: comprehensions.
List.init 4 (fun _ -> [])
[for _ in 1..4 -> []]
Or any sane language that uses immutable values by default like Elixir, Erlang, Clojure, Racket, Scheme, OCaml, etc.> Actually, if you really want to have re-evaluting (sub)expressions, then Python does give you an option: comprehensions.
That's the complaint, that [[]]*4 is not shorthand for list comprehensions and that it's something entirely different. This is common in Python where two things you'd expect to be the same are indeed different in subtle ways.
List comprehensions in Python are closer to sane, but they still have unexpected behavior because of the way scoping works in Python.
I think the small example is misguiding the intuition here.
If I write `my_list = f(expensive operation); long_list = my_list * 4`, I don't expect python to recreate the whole thing four times. I justly assume `f` will be evaluated once, and then copied.
That's not what you're asking for, though. You're asking for one bucket, and then you're putting it in another bucket, and then you're duplicating the contents of the second bucket four times.
This isn't whitewashing, this is just what those expressions mean.
It's not like it's hard to get four buckets in Python, BTW:
[[] for _ in range(4)]I don't get how this is an example of python mixing up mutable/immutable data, and I'm unaware of a situation where python does. Conceptually I'm not even sure what you mean by a language 'mixing up mutable and immutable data' unless it's literally just a buggy/non hardened implementation.
A = (1, ); A[0] = 2 # this raises an exception
> In more sane languages, the expression [] means give me an empty list value, nothing more and nothing less
What is an “empty list value”?
a = []
b = [a]*4
a.append(1)
print(b)
I mean it is possible to change Python and make [...]*n a shorthand for "repeat this statement n times" but that would be odd on its own.Lists pass by reference, tuples pass by value, if you want to understand Python you're just going to have to get used to that distinction. There are other options, but most are worse.
Is that true? I haven't looked at the implementation so I can't say it's impossible, but it would be extremely surprising to me if tuples passed by value, because tuples longer than the size operated upon my individual processor instructions would become expensive to pass around.
From a correctness perspective the difference between pass-by-reference and pass-by-value (pass-by-copy) aren't usually important, but for performance it can be a very large difference.
My argument is that that distinction isn't needed, by default, in a high-level language, and that plenty of people get it wrong, understandably. It is simply complexity that is not needed.
These simple examples can be toyed with, but sooner or later one is going to want to solve real problems, and unintuitive, default behavior doesn't help with that. Python's mode of operation tends to favor implicit over explicit. And the syntax [...]*n is implicit.
No, I didn't know that, and I'd guess that the vast majority of Python developers don't, because people don't generally learn Python by reading the docs front to back and finding out the official names of everything.
> It's a value that's reused for every function call, not an expression that re-evaluated at every function call.
No one is confused about that. I'm aware that's how it is, but is that how it should be? I.e. if we could choose for this to be reused for every function call or re-evaluated every function call, which results in more intuitive behavior?
> a = [0]
and
> b = [0]
these two expressions produces different 'value' objects for `[0]`, and modifying `a.append(a[-1] + 1)` does not change b.
so it's unintuitive that using `[0]` as a default value in a function argument can cause that argument to retain the same value across multiple function calls, when programmers would assume the argument to a function is not the same across multiple invocations.
The issue really here is the usage of an array object, which is not a value object (immutable), but a reference object. It would not have been a problem if the default argument was a string, or a number.
This is a reason not to use arrays in default arguments.
On the other hand, if we abstract from the technical minutiae, yes, it would have been entirely possible for Python to treat default arguments in the function definitions as expressions, by using machinery similar to what gets used for comprehensions: after all, as you point out, function's arguments (and local variables) do get re-assigned on every function call.
They are part of function definition, they aren't in the function body. You should expect them to be "executed" when the function is defined.
In this case, the default arguments get compiled as part of the function code and are part of the function's environment. As a result every time that function is called it is always having the same environment, i.e. the default argument values are not reinterpreted on every invocation. So the mutations to the environment are visible across function calls.
Yeah, I understand that; I'm saying that was a choice they made, and I think having the defaults be evaluated at each call time would have been a better choice.
Alternatively, the issue is that Python does not distinguish between value and reference types.
I’m not even a python guy, if you think I’m biased. These questions are natural for a programmer and a programmer has to ask themselves about what they expect, why, is it consistent, is it safe to assume.
Making [[]]*4 to create three new lists implies that you add a non-obvious ephemeral re-evaluation point in your grammar. Should [[f()]]*4 call f() three more times?
These may be added for convenience. But you have to make sure that syntactic context makes it dead clear. E.g. in a for-i iterator part, loop conditions, function argument init, etc. Locations which are known to be executed more than once. (Python specifically doesn’t even do that for arguments. Every def f(x=[]) shares the same list as a default for x.)
class X: pass
y = [X()] * 5
and suddenly I think the behaviour looks fairly reasonable.
My bigger question is how does a professor of machine learning does not know about one of the oldest Python footguns to exist:
https://stackoverflow.com/questions/12791501/why-does-this-c...
Very nice article otherwise, I never actually bothered looking into why it behaved this way(at this point most people initialize using list comprehension, so this bug is IMO very rare in production), very well explained.
Because there's a lot of them. And as soon as you touch a sane language that fits your intuitive model of how things should work, going back to Python means that you'll start doing intuitive things that Python will happily and silently transform into unintuitive operations.
I started using loops and it motivated me to start writing list comprehensions. One of the foot guns that will really motivate you to understand Python as a tool more than anything.
One of them goes into how many lines of C it takes to execute "a + b" in Python (great explanation, but you have to go to the comments for the answer!). I remember one of my professors opening up gdb and printing every C line to execute "print("hello, world")", and the author's writings give a better understanding of what some of those lines are.
I'd be very interested in a follow-up post going in-depth on the ins and outs of list comprehension.
I have not looked into list comprehensions. I think that and how generators work internally might be interesting to write about. I will try to cover them.
[[] for _ in range(N)]
Since generator-like expressions evaluates the inner expression (i.e. the []) on each iteration, the elements of the outer list are guaranteed to be unique references. #good
a = [True] * 8 # bool is primitive
b = [[True] * 8 for i in range(8)] # range creates new lists each time
#bad
a = [{}] * 8 # dict is not a primitive
b = [[True] * 8] * 8 # list is not a primitiveThere just happen to be some types where you cannot change the referenced value in any way. These behave like value types in other languages.
(If you believe that they should be marked explicitly, do you also believe the same thing about Rust? I.e. should the Rust compiler throw an error if you never actually change a reference type, as you "should" be using a value type in that case?)
If you had done [1] * 4 you'd ended up with a list of four references to the same object (1) as well. It's just that 1 isn't mutable, so nobody cares.
Only context I've ever found it useful in, is if you're unit testing something that accepts a string of max length M, then
bad_str = "A" * (M + 1)
Is quite nice and also, easy to interpret.But if you're calling multiply on a list[list[Any]] lol nah mate, what the hell are you playing at, make a for loop and add comments.
It's also remarkebly easy to diagnose once you see the unexpected behaviour, so anyone asking for help is going to be instantly told not to do it and use a comprehension instead.
I'm sure there are plenty of other pitfalls in other languages, though I concede this one is especially unintuitive to a new person.
On a mutable sequence. Or anything mutable. [] being a sequence is not the issue here.
If you work with immutable stuff, * is really not an issue.
'a'*3 == 'a'+'a'+'a'
I think Erlang got this one right.
Perhaps folks replace their containers and fundamental types like strs, lists, and dicts with immutable ones using an appropriate library.
The higher-level a programming language is, the more likely it is to hide the use of references, and also the more likely it is to hide when a new object is created, which would break shared mutable state.
In C or Go any reference is taken explicitly and objects are also created explicitly, so it's very easy to see at a glance what can be mutated from outside the immediate scope or when a defensive copy is made.
Java and C# use lots of implicit references but still require keyword new for nearly all object instantiations. It's easy to look at the expression Collections.nCopies(4, new ArrayList<>()) and understand that the same list will be referenced 4 times.
At the highest extreme you have languages like Haskell where immutability makes details about when objects are copied or referenced irrelevant. Surprising behaviour is outright impossible now.
Python appears to be in a tarpit where object instantiation and referencing is obscured just enough that it can take you by surprise when it silently results in shared mutable state.