Python Pickle Module and OOP -


in example below pickle crashes every attempt save instance file.

why happen?

how avoid it?

how around it?

class base(dict):     def __init__(self):         super(base, self).__init__()  class classa(base):     def __init__(self):         super(classa, self).__init__()       def setinstb(self, instb):         self['instb']=instb  class classb(base):     def __init__(self):         super(classb, self).__init__()     def setinsta(self, insta):         self['insta']=insta  insta=classa() instb=classb()  insta.setinstb(instb) instb.setinsta(insta)  import pickle pickle.dump( insta, open( "save.p", "wb" ) ) 

posted later.

if base(dict) class not declared subclass of built-in dict problem goes away. running code posted below raises no pickle errors. still want know why pickle fails , how make work classes inheriting dict.

class base(object):     def __init__(self):         super(base, self).__init__()  class classa(base):     def __init__(self):         super(classa, self).__init__()       def setinstb(self, instb):         self.instb=instb  class classb(base):     def __init__(self):         super(classb, self).__init__()     def setinsta(self, insta):         self.insta=insta  insta=classa() instb=classb()  insta.setinstb(instb) instb.setinsta(insta)  import pickle pickle.dump( insta, open( "save.p", "wb" ) ) 

i think ran kind of bug in pickle. suggest submit it, , fixed.

following code can fix problems:

# -*- coding: utf-8 -*- class base(dict):     def __init__(self):         super(base, self).__init__()         pk = none  class classa(base):     def __init__(self):         super(classa, self).__init__()     def setinstb(self, instb):         self['instb']=instb  class classb(base):     def __init__(self):         super(classb, self).__init__()     def setinsta(self, insta):         self['insta']=insta  insta=classa() insta.pk=1 instb=classb() instb.pk=2  insta.setinstb(instb) instb.setinsta(insta)  import pickle  class mypickler(pickle.pickler):     def persistent_id(self, obj):         return obj.pk  mypickler(open( "save.p", "wb" )).dump(insta) 

pickler allows explicitly generate unqie ids objects: see persistent_id method, , since these database objects guess generating ids easy.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -