Using copyreg to pickle unpicklable oblects
Peter Otten
__peter__ at web.de
Mon Sep 19 12:47:18 EDT 2016
kerbingamer376 wrote:
> Hi,
[No need to start a new thread for this]
> I have an object (pygame.mixer.Sound) and, to convert it to a picklable
> format, I can run:
>
> sound_object.get_raw()
>
> and to turn that back into an object, I can run:
>
> sound_object = pygame.mixer.Sound(raw_data)
>
> Is it possible to use copyreg or something similar so it's done
> automatically when I pickle pygame.mixer.Sound() objects?
Have a look at the example from the documentation:
>>> import copyreg, copy, pickle
>>> class C(object):
... def __init__(self, a):
... self.a = a
...
>>> def pickle_c(c):
... print("pickling a C instance...")
... return C, (c.a,)
...
>>> copyreg.pickle(C, pickle_c)
Translating that gives (untested)
import copyreg # copy_reg in Python 2
import pygame.mixer
def pickle_sound(sound):
return pygame.mixer.Sound, (sound.get_raw(),)
copyreg.pickle(pygame.mixer.Sound, pickle_sound)
Does that work?
More information about the Python-list
mailing list