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

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

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


  1. Anonymous4:48 PM

    why not hasattr ?

  2. hasattr also work for checking attribute exist in a object.

    it just that i kinda like the dict convention, one less function to remember.

    also, it is nice to generate out a list of attribute that we created in a objects like obj.val = 'val'

  3. Anonymous8:58 PM

    dir(obj) lists all attributes including functions.

    checking attribute existence __dict__ is so not pythonic.

  4. Enlightened i am.

    after read the doc, dir is a better idea....