Simple Python __str__(self) method for use during development

For my development work I want a simple way to display the data in an object instance without having to modify the __str__(self) method every time I add, delete, or rename members. Here's a technique I've adopted that relies on the fact that every object stores all of its members in a dictionary called self.__dict__. Making a string representation of the object is just a matter of returning a string representation of __dict__. This can be achieved in several ways. One of them is simply str(self.__dict__) and the other uses the JSON serializer json.dumps(), which lets you prettyprint the result.

Here's a little Python demonstrator program:

# /usr/bin/python

""" demo - demonstrate a simple technique to display text representations
    of Python objects using the __dict__ member and a json serializer.

    $Id: demo.py,v 1.3 2015/07/18 13:07:15 marc Exp marc $
"""

import json

class something(object):
    """ This is just a demonstration class. """
    def __init__(self, id, name):
        self.id = id
        self.name = name

    def rename(self, name):
        self.name = name

    def __str__(self):
        return json.dumps(self.__dict__, indent=2, separators=(',', ': '))
        # return str(self.__dict__)

def main():
    o1 = something(1, "first object")
    o2 = something(2, "second object")

    print str(o1)
    print str(o2)

    o1.rename("dba third object")

    print str(o1)

if __name__ == '__main__':
        main()

Running it produces this output:

$ python demo.py
{
  "id": 1,
  "name": "first object"
}
{
  "id": 2,
  "name": "second object"
}
{
  "id": 1,
  "name": "dba third object"
}

Nice and easy for testing and debugging. Once I'm ready for production and no longer want the JSON representations I can introduce a DEBUG flag so that the non-DEBUG behavior of __str__(self) is appropriate to the production use.

[update]

What's wrong with this?  If I have a member that is itself an object, then the json.dumps() call fails.  Ideally Python would call __str__() on a member if __str__() was called on the object.

On reading some more goodies, it's clear that what I should be using is repr() and not str().

Comments

Popular posts from this blog

Quora Greatest Hits - What are common stages that PhD student researchers go through with their thesis project?

Two Intel NUC servers running Ubuntu

Monthly Payment Tracker spreadsheet