Search code examples
pythonnscodingobject-persistence

Is there an NSCoding-like facility in Python?


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?


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