Question

As an iOS developer recently experimenting with Python, I'm curious to know if there's something like NSCoding that would allow me to implement a method or a pair of methods which would define how my objects can be automatically saved to disk, much like NSCoding.

I've found this repo but I'm not sure if it's part of a larger framework, which I'd rather not incorporate into my (small) project.

Is there something that ships with Python? Anything popular out there that deals with object persistence in a primitive yet powerful way?

Was it helpful?

Solution

The pickle module is used for serializing objects.

http://docs.python.org/2/library/pickle.html

You can usually just use it as-is, but if you need to define how objects should be serialized, you can override the special methods, __getstate__ and __setstate__

import cPickle as pickle # faster implementation

path = 'test.dat'
obj = ('Hello, world!', 123, {'x': 0})

# save to disk
with open(path, 'wb') as fp:
    pickle.dump(obj, fp)

# load from disk
with open(path, 'rb') as fp:
    obj = pickle.load(fp)

print obj

OTHER TIPS

As for __getstate__ and __setstate__ implementations here are some notes:

  1. You don't really need to implement these, all objects are pickleable by default. So unless your objects hold things like: files, sockets, database connections and so on, they are pickleable.
  2. Basically __getstate__ should return something that is pickleable. And __setstate__ (after loading from disk) will reclieve this object as it's sole argument, and should reconstruct current instance. Most implementations of __getstate__ return either touple or dict, but I guess it is up to you.
  3. Mind that overriding these methods will also change how copy.copy and copy.deepcopy work (can be a serious pain if you do some validation inside these methods).

As for example implementation take look at this (it is a snipped from my code, and here I override pickle methods from some superclass):

def __getstate__(self):
    state = super(Simulation, self).__getstate__()
    state['usercode'] = self.usercode
    return state

def __setstate__(self, state):
    super(Simulation, self).__setstate__(state)

    self.usercode = state.get('usercode', 'dosrznrc')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top