unpickling Set as set

A

Amir Michail

Hi,

Is there an easy way to unpickle the older Set as the newer set behind
the scenes when using shelve?

Amir
 
N

Nick Vatamaniuc

The two are not of the same type:

---------------------------------
In : import sets
In : s1=sets.Set([1,2,3])

In : s2=set([1,2,3])

In: type(s1)
Out: <class 'sets.Set'>

In : type(s2)
Out: <type 'set'>

In : s1==s2
Out: False # oops!

In: s2==set(s1)
Out: True # aha!
----------------------------------

You'll have to just cast:
unpickled_set=set(unpickled_set)

-Nick V.
 
G

George Sakkis

Nick said:
The two are not of the same type:

---------------------------------
In : import sets
In : s1=sets.Set([1,2,3])

In : s2=set([1,2,3])

In: type(s1)
Out: <class 'sets.Set'>

In : type(s2)
Out: <type 'set'>

In : s1==s2
Out: False # oops!

In: s2==set(s1)
Out: True # aha!
----------------------------------

You'll have to just cast:
unpickled_set=set(unpickled_set)

-Nick V.


Or you may have this done automatically by hacking the Set class:

from sets import Set
import cPickle as pickle

Set.__reduce__ = lambda self: (set, (self._data,))

s = Set([1,2,3])
x = pickle.dumps(s)
print pickle.loads(x)


This doesn't work though if you have already pickled the Set before
replacing its __reduce__, so it may not necessarily be what you want.
If there is a way around it, I'd like to know it.

George
 
G

Gabriel G

Or you may have this done automatically by hacking the Set class:

from sets import Set
import cPickle as pickle

Set.__reduce__ = lambda self: (set, (self._data,))

s = Set([1,2,3])
x = pickle.dumps(s)
print pickle.loads(x)


This doesn't work though if you have already pickled the Set before
replacing its __reduce__, so it may not necessarily be what you want.
If there is a way around it, I'd like to know it.

Perhaps registering a suitable reduce function in the copy_reg module.
If the sets were pickled alone, and it's not too much trouble, using:
a_set = set(a_set) just after unpickling may be enough.
And if they were instance attributes, __setstate__ on the class can
do the conversion.


--
Gabriel Genellina
Softlab SRL

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
 

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,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top