Pickling array.array

N

Nicolas Fleury

Hi,
Does anyone know if arrays would be picklable in python 2.4? Until
then, I tried to derive from array.array and add __setstate__ and
__getstate__ with the following code, but it seems I'm not doing it
correctly. Any idea what I'm doing wrong?

Thx and Regards,
Nicolas

import array as arr

class array(arr.array):
def __getstate__(self):
return {'buffer': self.tostring()}
def __setstate__(self, dict):
self.fromstring(dict['buffer'])
 
N

Nicolas Fleury

Nicolas said:
class array(arr.array):
def __getstate__(self):
return {'buffer': self.tostring()}
def __setstate__(self, dict):
self.fromstring(dict['buffer'])

I also added __getinitargs__(), but it is not called...
 
N

Nicolas Fleury

Nicolas said:
I also added __getinitargs__(), but it is not called...

For those interested in the same problem, the only solution I've found
is to encapsulate the array instead of derive from it. It sucks a bit,
since all methods need to be implemented to redirect to array.array, but
at least it's working. I'm still wondering how to do it with derivation...

Thx and regards,
Nicolas

import array as arr
class array:
def __init__(self, typecode, initializer=None):
self.arr = arr.array(typecode, initializer)
def __getstate__(self):
return {'buffer': self.arr.tostring(),
'typecode': self.arr.typecode}
def __setstate__(self, dict):
self.arr = arr.array(dict['typecode'])
self.arr.fromstring(dict['buffer'])
 
N

Nicolas Fleury

Nicolas said:
For those interested in the same problem, the only solution I've found
is to encapsulate the array instead of derive from it. It sucks a bit,
since all methods need to be implemented to redirect to array.array, but
at least it's working. I'm still wondering how to do it with derivation...

Here's a complete solution (if anyone knows a simpler solution...):

import array as arr
class array:
def __init__(self, typecode, initializer=None):
self.arr = arr.array(typecode, initializer)
def __getstate__(self):
return {'buffer': self.arr.tostring(),
'typecode': self.arr.typecode}
def __setstate__(self, dict):
self.arr = arr.array(dict['typecode'])
self.arr.fromstring(dict['buffer'])
def __getattr__(self, name):
if name == 'arr': return self.arr
return self.arr.__getattribute__(name)
def __setattr__(self, name, value):
if name == 'arr': self.__dict__['arr'] = value
else: self.arr.__setattr__(name, value)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top