Pickling Robustly
jepler epler
jepler.lnk at lnk.ispi.net
Sat Apr 22 22:31:20 EDT 2000
On 21 Apr 2000 14:06:28 -0500, Glyph Lefkowitz
<glyph at twistedmatrix.com> wrote:
>Perhaps I should ask this question in a different way. How does
>Pickle tell if an object is pickleable or not? Is there some
>pickle.ispicklable method I could refer to?
If you have control over the object hierarchy, why not use this
'unpicklable mixin' and convenience functions I just tossed together:
import pickle, UserList
class Unpicklable:
def __getinitargs__(self):
raise Unpicklable
def ispicklable(a):
"""This tests if a can be pickled (by actually trying to do so)"""
try:
pickle.dumps(a)
except Unpicklable:
return 0
return 1
def ispicklableinstance(a):
"""Note that this function does not tell whether a ultimately
contains an unpicklable instance. But at least it's a simple test.""
return isinstance(a, Unpicklable)
def ispicklableclass(A):
"""Note that this function does not tell whether an instance
might ultimately be unpicklable due to something nested inside it."""
return issubclass(a, Unpicklable)
if __name__=='__main__':
class UserListU(UserList.UserList, Unpicklable): pass
x = UserList.UserList([1,2,3])
print pickle.dumps(x)
y = UserListU([1,2,3])
print pickle.dumps(y) # This will cause an exception
Jeff
More information about the Python-list
mailing list