The Art of Pickling: Binary vs Ascii difficulties

Bix bix_mix at hotmail.com
Thu Oct 14 21:28:58 CEST 2004


As this is my very first post, I'd like to give thanks to all who
support this with their help.  Hopefully, this question hasn't been
answered (too many times) before...

If anyone could explain this behavior, I'd greatly appreciate it.

I'm leaving the example at the bottom.  There is a variable, fmt,
within the test0 function which can be changed from -1
(pickle.HIGHEST_PROTOCOL) to 0 (ascii).  The behavior between the two
pickle formats is not consistent.  I'm hoping for an explaination and
a possible solution; I'd like to store my data in binary.

Thanks in advance!


# example.py
import pickle
class node (object):
	def __init__ (self, *args, **kwds):
		self.args = args
		self.kwds = kwds
		self.reset()

	def reset(self):
		self.name = None
		self.node = 'node'
		self.attributes = {}
		self.children = []
		self.update(*self.args,**self.kwds)

	def update(*args,**kwds):
		for k,v in kwds.items():
			if k in self.__dict__.keys():
				self.__dict__[k] = v
	
def test0 (x,fmt=-1):
	fn = 'out.bin'
	pickle.Pickler(open(fn,'w'),fmt).dump(x)
	obj = pickle.Unpickler(open(fn,'r')).load()
        return obj

def test1 ():
	x = node()
	return test0(x)

def test2 ():
	x = node()
	y = node()
	x.children.append(y)
	return test0(x)

def test3 ():
	w = node()
	x = node()
	y = node()
	z = node()
	w.children.append(x)
	x.children.append(y)
	y.children.append(z)
	return test0(w)

def test4 ():
	w = node()
	x = node()
	y = node()
	z = node()
	w.children.append(x)
	x.children.append(y)
	y.children.append(z)
	return test0(w,0)

def makeAttempt(call,name):
	try:
		call()
		print '%s passed' % name
	except:
		print '%s failed' % name

if __name__ == "__main__":
	makeAttempt(test1,'test1') # should run
	makeAttempt(test2,'test2') # should run
	makeAttempt(test3,'test3') # should fail
	makeAttempt(test4,'test4') # should run



More information about the Python-list mailing list