1. 8
  1.  

  2. 8

    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.

    1. 1

      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.

    2. 2

      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.

      1. 1

        I think that the author is pointing out tweets that he disagrees with, not saying that “read-only list” is a bad explanation.

        Note:

        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.

      2. 1

        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.

        1. 1

          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.

          1. 1

            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.