Type-checking unpickled objects

G

Gordon Airporte

I have this class, and I've been pickling it's objects as a file format
for my program, which works great. The problems are a.) how to handle
things when the user tries to load a non-pickled file, and b.) when they
load a pickled file of the wrong class.

a. I can handle with a general exception I guess. I just tried to
pickle.load() a .pyc and it failed with a 'KeyError' exception - however
that works. It might do that every time, it might not.

Regarding b., if I type check I simply get the 'instance' type, which
doesn't get me all of the way there because I might have an instance of
the wrong class. I can't find any sort of __type__ attribute to set in
the objects. Perhaps I should use __str__?
 
F

Fredrik Lundh

Gordon said:
I have this class, and I've been pickling it's objects as a file format
for my program, which works great. The problems are a.) how to handle
things when the user tries to load a non-pickled file, and b.) when they
load a pickled file of the wrong class.

a. I can handle with a general exception I guess. I just tried to
pickle.load() a .pyc and it failed with a 'KeyError' exception - however
that works. It might do that every time, it might not.

I hope you're aware of the fact that pickle is not suitable for applications
where you cannot trust the source; see e.g.

http://www.livejournal.com/users/jcalderone/15864.html

(one of the comments show how to place restrictions on what can be loaded
from a given pickle)
Regarding b., if I type check I simply get the 'instance' type, which
doesn't get me all of the way there because I might have an instance of
the wrong class. I can't find any sort of __type__ attribute to set in
the objects. Perhaps I should use __str__?

how about a plain

obj = cPickle.load(...)
if not isinstance(obj, Class):
print "expected a Class instance"

</F>
 
G

Gordon Airporte

isinstance! Now why didn't I know about that? Thanks you. I guess I'll
need a throwaway instance of the class to run type() on to get a usable
type object for comparison, but I'll work something out.
As to the security considerations...this is a small enough program with
a limited enough release that I'm not going to sweat it, although I will
keep this in mind.
 
G

Gordon Airporte

I guess I'll
need a throwaway instance of the class to run type() on to get a usable
type object for comparison, but I'll work something out.

Never mind - I can just pass the name of the class, as it should be.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top