Wednesday, June 22, 2011

Usefulness of __dict__

I am writing a validation function to check for objects instance, in this case, it is a django models. The object is mostly the same, except there is a extra field that need to be checked, that field exist only in certain object, but not all object.

So being lazy, I use the __dict__ special attribute. It exist in every python object, and contains symbol tables of the object, which I can use to check for existence of a attribute. For example

"""
>>> s = Sample()
>>> s.__dict__
{'test_val':1,'another_val':'a'}
>>> 'test_val' in s.__dict__
True
"""
class Sample:
def __init__(self):
self.test_val = 1
self.another_val = 'a'
view raw sample.py hosted with ❤ by GitHub

so we can do thing like check a item like 'test_val' in c.__dict__ to check for a existence of a attribute. 

From the same idea, one very cool thing to do is, convert get the __dict__ and convert the attribute into a json object, with example

import json
"""
>>> c = C()
>>> c.a = 1
>>> c.b = 2
>>> c.__dict__
{'a':1,'b':2}
>>> c.to_json()
'{"a":1,"b":2}'
>>> json.dumps(c.__dict__)
'{"a":1,"b":2}'
"""
class C:
def to_json(self):
json.dumps(self.__dict__)
view raw object2json.py hosted with ❤ by GitHub

One idea I have been playing is, because django model instance is essentially a objects, we can use the same idea, to output the value in a single django model instance into a json string, but we need to be careful on certain data type like double etc. 

The big catch is of using this is, __dict__ only contains attributes of a objects, it does not contain built-in attributes, and it does not contain methods. So if a value is from a method, you need to think of another way. Which actually sucks, as I have a lot of such methods in my classes, well I probably figure out by that time.

So, happy coding