Tuesday, April 29, 2014

Convert Your Custom Object to a Dictionary

Creating your own classes is a great in python.  It's easy and straight forward, and allows python users to mask repetitive code in our scripts, and create custom packages.

Let's assume that you are working with JSON, and you want to create a bunch of custom classes that return the data stored inside of them back as dictionaries.  This can be easily done by implementing the __iter__() in the class you are designing.

The function __iter__() returns an iterator object.  The object is required to support the iterator protocol.

For example, take the class below:

import json
class test(object):
    _a = None
    _b = None
    def __init__(self, a,b):
        self._a = a
        self._b = b
    def a(self):
        return self._a
    def b(self):
        return self._b
    def __str__(self):
        """ returns object as string """
        o = {}
        for k,v in self.__iter__():
            o[k] = v
        return json.dumps(o)
    def __iter__(self):
        """ iterator generator for public values/properties """
        attributes = [attr for attr in dir(self)
                      if not attr.startswith('__') and \
                      not attr.startswith('_')]
        for att in attributes:
            yield (att, getattr(self, att))

Here __iter__() and __str__() are implemented, along with two properties 'a' and 'b'.  From the user's standpoint, they are probably only interested in the public properties, so in the __iter__(), the properties without '__' and '_' are returned in a key/value pair object.  __str__() returns the data as JSON using the json library built into python.  __str__ is another built in class that is called when you do either a print or print str().

The result if you print out as a string is: {"a": 1, "b": 2}
For the dictionary: {'a': 1, 'b': 2}

The first is a string and the second is dictionary.


No comments: