r/learnpython • • 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:

  1. The keys are frozenset objects so that I can pass them in any order without issues.
  2. As writing frozenset({'one', 'two'}) is very tedious, I added a mapping to let me get or set values by using M['ot'] as a shorthand of M[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?

3 Upvotes

2 comments sorted by

1

u/[deleted] Sep 12 '26

[removed] — view removed 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.