ispicklable() --> bool, possible?
Gerrit Holl
gerrit at nl.linux.org
Mon Feb 24 18:10:36 EST 2003
Hi,
I am currently using the following code to check whether an object is
picklable or not:
_canpickle = (NoneType, bool, int, long, float, complex, basestring, FunctionType, ClassType)
_cantpickle = (GeneratorType, pygame.sprite.Group, pygame.sprite.GroupSingle, pygame.sprite.Sprite, pygame.rect.Rect, pygame.Surface)
def picklable(obj):
for inst in _canpickle:
if isinstance(obj, inst):
return True
for inst in _cantpickle:
if isinstance(obj, inst):
return False
if isinstance(obj, dict):
obj = obj.values()
if isinstance(obj, list) or isinstance(obj, tuple):
for subobj in obj:
if not picklable(subobj):
return False
return True
debug("unknown", obj)
try:
cPickle.dumps(obj)
except (TypeError, cPickle.UnpickleableError):
return False
else:
return True
However, this has problems. For instance, a list can be recursive,
which causes this function to loop. An obj can contain itself, and
if the obj's __getstate__ calls picklable, this function loops. The
latter was true in my case, because I'm using my function to check
whether I should do a certain operation on my instances' __data__
or not dependant on among others the result of picklable().
Is there a better, clean way to check whether an object is picklable
or not? I have not found any such function is the pickle library.
Nor have I found it in the standard library. Not have I found it on
the internet. Nor have I found it in the archives. Nor have I found
out whether it is theoratically possible. Nor have I found out whether
to spell picklable with or without the trailing 'e' of pickle (i.e.
pickleable or picklable).
yours,
Gerrit.
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
http://www.sp.nl/
More information about the Python-list
mailing list