4

Using Python 2.7. Is there a way to restore only specified objects from a pickle file?

using the same example as a previous post:

import pickle

# obj0, obj1, obj2 are created here...

# Saving the objects:
with open('objs.pickle', 'w') as f:
    pickle.dump([obj0, obj1, obj2], f)

Now, I would like to only restore, say, obj1

I am doing the following:

with open('objs.pickle', 'r') as f:
    obj1=pickle.load(f)[1]

but let's say I don't know the order of objects, just it's name. Writing this, I am guessing the names get dropped during pickling?

Community
  • 1
  • 1
jlarsch
  • 2,217
  • 4
  • 22
  • 44
  • you can use different files for the different objects or pickle a list and store an index in another file – maazza Mar 09 '16 at 10:43

2 Answers2

3

No. Python objects do not have "names" (besides some exceptions like functions and classes that know their declared names), the names are just pointing to the object, and an object does not know its name even at runtime, and thus cannot be persisted in a pickle either.

Perhaps you need a dictionary instead.

Community
  • 1
  • 1
3

Instead of storing the objects in a list, you could use a dictionary to provide names for each object:

import pickle

s = pickle.dumps({'obj0': obj0, 'obj1': obj1, 'obj2': obj2})

obj1 = pickle.loads(s)['obj1']

The order of the items no longer matters, in fact there is no order because a dictionary is being restored.

I'm not 100% sure that this is what you wanted. Were you hoping to restore the object of interest only, i.e. without parsing and restoring the other objects? I don't think that can be done with pickles without writing your own parser, or a fair degree of hacking.

mhawke
  • 84,695
  • 9
  • 117
  • 138