Last week I started working in Python again. I’m seeing tuples again with a new eyes and taking notes towards another talk. Thanks to HPFFP I recognize them as anonymous products. Tuples are ad hoc data types and I have a sneaking suspicion that they only exist because the overhead of defining and using types is too high. A class is at least two lines of code, more likely three, and you have to start writing tests to verify any behvaior. Destructuring Python classes is clunky and custom (you have to write and know accessors instead of language syntax), and changing the definition is a recipe for bugs because you can’t lean on a type checker to find all the instances to update.
It would be nice if Python had some way to define tuples with a named constructor, but anonymous positional arguments. (Think Rust’s tuple structs.) Of course, without using ugly hacks like namedtuple.
I haven’t ever really thought of the distinction, but looking over the list of usages, I think that tuples feel the most pythonic in situations where the arity is fixed. Overloading tuple as “read-only list” is of course possible but feels like a waste of tuple as vocabulary.
It’s kinda weird that this post starts off as pointing to the “read-only list” as a bad explanation, but then basically recommends using tuples as read-only lists.
I think that the author is pointing out tweets that he disagrees with, not saying that “read-only list” is a bad explanation.
Now to start off, I want to say that I respect the hell out of David Beazley. The guy literally wrote the book on Python, and he knows way more about Python than I ever will. He’s also one of the most entertaining Python people you can follow on Twitter. But hey, that doesn’t mean I can’t disagree sometimes.
Ned Batchelder writes well on lists vs tuples. I also added a comment when that essay appeared on HN, that tuples also have an important syntactic difference that is often overlooked.
If you know enough about python’s list vs tuple implementation that tuples aren’t just read-only lists… you probably don’t need that book to start with.
Another thing that the author didn’t really touch on is other programming languages. In (most?) other programming languages, a tuples is not an immutable list. For example, it Haskell, each tuple element may have a different type whereas all list elements must be the same type. In addition there is no way to iterate over an n-tuple in a generic way in Haskell.