[IronPython] Portable use of pickle.dumps()

Robert Smallshire robert at smallshire.org.uk
Fri May 29 23:00:18 CEST 2009


Michael,

> Michael Foord wrote:
> > [snip...]
> > Here is an example of getting a byte array from a binary pickle in
> > IronPython:
> >
> > >>> import pickle
> > >>> class A(object):
> > ...  b = 'hello'
> > ...  c = (None, 'fish', 7.2, 7j)
> > ...  a = {1: 2}
> > ...
> > >>> p = pickle.dumps(A(), protocol=2)
> > >>> p
> > u'\x80\x02c__main__\nA\nq\x00)\x81q\x01}q\x02b.'
> > >>> from System import Array, Byte
> > >>> a = Array[Byte](tuple(Byte(ord(c)) for c in p))
> > >>> a
> > Array[Byte]((<System.Byte object at 0x0000000000000033 [128]>,
> > <System.Byte obje...
> >
> 
> And the converse:
> 
>  >>> p2 = ''.join(chr(c) for c in a)
>  >>> a2 = pickle.loads(p2)
>  >>> a2
> <A object at 0x000000000000004E>
>  >>> a2.a
> {1: 2}
>  >>> a2.b
> 'hello'
>  >>> a2.c
> (None, 'fish', 7.2, 7j)

As a result of applying your str <--> Array[Byte] transformations to my
code, the persistence of pickles into SQLite BLOBs is now working as
planned. :-)

You'll also no doubt be pleased to hear that even with these extra
transformations, the IronPython version is around twice as fast as CPython
2.6 on a benchmark performed under completely unscientific conditions -
although there are many factors at play here...

Thanks again,

Rob




More information about the Ironpython-users mailing list