How to create a Persistable Dictionary in Python

I came across a situation where I had to implement a Python class which can;

  • handle dynamic attributes
  • can be initialized with a dictionary
  • can be persisted on the local storage as a file
  • can be used as a dictionary as well as a object. ( allow both  foo['key']  and  foo.key  to access its attributes )

So I came up with this Class. It inherits from python’s built in Dictionary class ( dict ). Therefore it can be initialized with an existing dictionary.  And it also overrides  __getattr__   __setattr__  __delattr__ . Therefore it can handle dynamic attributes and act as a dictionary as well as a object. Finally It uses Python’s cPickle to serialize and persist it self in the local storage.

Please share your thoughts on this approach. 🙂

Iterate and Initialize all sub classes in python

In various situations, we need a mechanism to Initialize all Sub classes for a given Super class. For instance, let’s assume that we have a Super class called ArithmeticOperation and another 4 classes derived from it (Addition, Subtraction, Multiplication and Division).

One way of doing it is Initializing each Sub class separately.

But if there are hundreds of Sub classes, we need to think of another mechanism.  That’s where .__subclasses__() becomes very useful. We can use that method to Iterate and Initialize all Sub classes for that given Super Class. You can do it like this,

Hope this post helped someone who’s looking for a way to Iterate and Initialize all Sub classes for a given Super Class using python. 🙂