Using copyreg to pickle unpicklable oblects

Peter Otten __peter__ at web.de
Mon Sep 19 15:19:01 EDT 2016


kerbingamer376 wrote:

> 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

Looks like Sound doesn't set the __module__ attribute correctly.
Try injecting it into the built-in namespace:

import builtins
builtins.Sound = pygame.mixer.Sound





More information about the Python-list mailing list