Don't use dicts so much

Posted on Fri, 09 Sep 2016 in Python

Python developers tend to use dicts too much. Mainly I tell about pass data through application as dicts not objects. It's a bad design witch causes many problems.

For example, our code calls external API and receives json (dict, actually). Should I pass this dict further or convert to the specific class? Both variants are possible, but I prefer to use classes and objects, although, it takes much more time and efforts to code.

This approach has some advantages. Such code is much easier to read. It's self-documented and maintainable.

Compare this:

def return_dict():
    response = responses.get("some_api")
    return response.json()

And this:

class SomeObject:
    def from_json(cls, json):
        instance = cls()
        // do magic
        return instance

def return_some_object():
    response = responses.get("some_api")
    return SomeObject.from_json(response.json())

What example is easier to read? What about maintainability?

I'm sure after a couple of months you forgot what return_dict returns. Event doc string doesn't help much. Response of such function validates very hard: usually such validation function is giant if-statement with many branches.

On the other hand, return_some_object return instance of the specific class. If you somewhere in your code receive such object, it's easy to discover what data it contains and what methods it provides. And if there is no documentation, it's quite easy to understand what this object is used for. In any case, it is much easier to deal with object of a specific class than dict.

Finally, code with classes much easier to maintain and test. Dict is to generic and say nothing about the data it contains. If dict contains nested dicts (with 99.99% probability), code maintenance becomes a nightmare.

Got a question? Hit me on Twitter: avkorablev