Upgrading from lists to objects

Friday 15 June 2007This is over 17 years old. Be careful.

Synchronicity abounds. Just as a blog post was forming in my mind, Kevin Dangoor wrote about the very same topic: Python dictionaries are not the same as instances. Python makes it so easy to cobble together ad-hoc data structures of lists and dicts, I find myself making do with them long past the time when I should have promoted them up to real classes.

It starts out simple, a function needs to return a list of strings. Fine. Then I need to add another piece of data for each string, so the result becomes a list of pairs. Another piece of data will turn it into a full-blown list of lists, and so on. Another function aggregates those results together, making a list of lists of lists, and so on.

I find I often live with this scheme beyond its tenable lifetime, like the boiling frog. Unlike Kevin’s scenario I usually don’t start with dicts, in my mind they naturally become classes: once you have to think up names for the components, classes are easy. It’s lists (with their unnamed components) that seem so simple to me that they gain favor where the “heavier-weight” classes won’t do.

But of course converting over to classes is not a big deal, and always reaps benefits. Kevin lists six, but overlooked the one that usually makes me smile first: default values in the constructor.

I don’t know that I will stop writing ad-hoc data structures, but maybe I’ll learn, and upgrade them to classes sooner. I just changed a data structure that was clearly over its limit: it was a list of four-element lists, the first element of which was a list of six-element lists:

[
    [ [ [a,b,c,d,e,f], [a,b,c,d,e,f], ... ],
        g, h, i ],
    [ [ [a,b,c,d,e,f], [a,b,c,d,e,f], ... ],
        g, h, i ],
    ...
]

The change makes it a list of objects, one of whose attributes is a list of objects. Much nicer. I shouldn’t have put it off so long.

Comments

[gravatar]
One clever way of dealing with this situation is to use tuples instead of lists -- in many cases, a tuple makes more sense than a variable-sized list as an ad-hoc data structure. Once the tuple becomes too limiting (for instance, when there are optional parameters), it's simple to change the tuple to a constructor for the more extensible class:
d = (1, 'hey', 0.5)
to this:
d = FrobNitz(1, 'hey', 0.5)

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.