Serializable decorator for Python Class

· 276 words · 2 minute read

I am going to describe a quick recipe for adding serializability to a Python Class. I was playing with Redis lately and needed a quick way to save python objects in Redis. I wanted objects to be saved in JSON format and found jsonpickle to be an appropriate module to use.

Initially I thought of having a base class with serialize/deserialize functions which other class could simple inherit to add serialize functionality. Here is the base class:

class Serializer():
  def serialize(self):
    return jsonpickle.encode(self)

    def deserialize(ser_str):
      return jsonpickle.decode(ser_str)

To add serialize functionality to a Python class, all i have to do is simply inherit from the above class shown below and I am done. (Note that deserialize is a static method)

class Visitor(Serializer): pass  

But then I thought of an elegant way of doing the same would be if I can specify a decorator @serializable while defining the class. So here is the code for decorater.

def serializable(cls):
  class wrapper:
    def __init__(self, *args):
      self.wrapped = cls(*args)
    def __getattr__(self, *args):
      return getattr(self.wrapped, *args)
    def serialize(self):
      return jsonpickle.encode(self.wrapped)

  def deserialize(ser_str):
    return jsonpickle.decode(ser_str)

  return wrapper

So now, I can simple specify the decorator on Visitor class to make it serializable as shown in following snippet.

class Visitor():
  def __init__(self, ip_addr = None, agent = None, referrer = None):
    self.ip = ip_addr = agent
    self.referrer= referrer
    self.time =

orig_visitor = Visitor('192.168', 'UA-1', '')
#serialize the object
pickled_visitor = orig_visitor.serialize()
#restore object
recov_visitor = Visitor.deserialize(pickled_visitor)

So this was it. Both the above approaches has got its GOOD and BAD. Do share your views about it. If you are interested in python decorators, you might find PythonDecoratorLibrary useful.