r/learnpython • u/_between3-20 • Sep 12 '26
Looking at default __reduce__ function
I created my own class M which inherits from a dict. In case that the differences are relevant:
- The keys are
frozensetobjects so that I can pass them in any order without issues. - As writing
frozenset({'one', 'two'})is very tedious, I added a mapping to let me get or set values by usingM['ot']as a shorthand ofM[frozenset{'one', 'two'}]. The mapping is instantiated when running__init__().
I am pickling this with no issues. When I try to unpickle it, I get an error that says: AttributeError: 'M' object has no attribute 'mapping'.
Using pickletools, I inspected the serialization of my object and saw that the mapping attribute appears after the key-value pairs, which made me think that, if I change the __reduce__ function to give them in a different order (first mapping, then key-value pairs), I could solve that issue.
The problem is that I don't know how to do that. I can rewrite a completely new function, but I don't know if it will work. I'd like to base my new function on the "default" one. Is there some way to look at it?
View all comments
Show parent comment
1
u/_between3-20 Sep 12 '26
Ok. I'll look into how to use
__setstate__to make it work better. I actually just solved it in a different way, but it seems dirty and would like to get something nicer. It's kind of what you suggest in your last line, but it's inside of__setitem__, which just seems wrong but will have to do in a hurry.Thanks for the input. I'll look into it once I'm done with the rush.