Using copyreg to pickle unpicklable oblects
kerbingamer376
martinjp376 at gmail.com
Mon Sep 19 14:10:08 EDT 2016
On Monday, September 19, 2016 at 5:48:35 PM UTC+1, Peter Otten wrote:
> 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?
I get:
_pickle.PicklingError: Can't pickle <class 'Sound'>: attribute lookup Sound on builtins failed
More information about the Python-list
mailing list