tag:blogger.com,1999:blog-29718960.post1200901290403325700..comments2022-04-03T04:35:05.965-07:00Comments on Western Skies: Simple, complete example of Python getstate and setstateCharles Andersonhttp://www.blogger.com/profile/02651484904301404333noreply@blogger.comBlogger3125tag:blogger.com,1999:blog-29718960.post-10952029908823479372010-01-19T09:17:06.758-08:002010-01-19T09:17:06.758-08:00""" cPickle Dotdict(dict) works w ...""" cPickle Dotdict(dict) works w protocol 0 but not -1 <br />"""<br />import cPickle<br />import sys<br /><br />class Dotdict(dict):<br /> """ d.x -> d["x"] """<br /> def __getattr__(self, attr):<br /> return self.get(attr, None)<br /> def __getstate__(self): # dumps<br /> return self<br /> def __setstate__(self, s): # loads<br /> self = s # ??<br /><br />if __name__ == "__main__":<br /> protocol = 0<br /> if sys.argv[1:]:<br /> exec( "\n".join( sys.argv[1:] ))<br /><br /> d = Dotdict( a=1 )<br /> print d.a, d["a"], d.get( "no", 42 ), d, d.keys(), "%(a)s" % d<br /> # 1 1 42 {'a': 1} ['a'] 1<br /> # print "%(no)s" % d<br /><br /> ddump = cPickle.dumps( d, protocol )<br /> # -1: TypeError: 'NoneType' object is not callable<br /> l = cPickle.loads( ddump )<br /> print "loads:", l<br /> assert d == l<br /><br />(grr no pre code ?)denishttps://www.blogger.com/profile/13342423091219074095noreply@blogger.comtag:blogger.com,1999:blog-29718960.post-3678628582822821102008-02-29T14:18:00.000-08:002008-02-29T14:18:00.000-08:00Good point. I hadn't thought of that, but so long...Good point. I hadn't thought of that, but so long as setstate and getstate are in-sync with each other, that would work. It could even be a string, but that would be kinda silly since pickling is trying to create a a string.Charles Andersonhttps://www.blogger.com/profile/02651484904301404333noreply@blogger.comtag:blogger.com,1999:blog-29718960.post-83612133122005305782008-02-29T12:03:00.000-08:002008-02-29T12:03:00.000-08:00"""As you can tell, __getstate__ returns a diction..."""As you can tell, __getstate__ returns a dictionary of the object's state."""<BR/><BR/>It doesn't have to. You could return a tuple, a list, a string, a number, or any other pickle-able value you like, if that's the only state you have.PJEhttps://www.blogger.com/profile/04688223805457202941noreply@blogger.com