Type-checking unpickled objects

Fredrik Lundh fredrik at pythonware.com
Sun Nov 20 09:07:02 EST 2005


Gordon Airporte wrote:

>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> 






More information about the Python-list mailing list