Behavior of OrderedDict._reduce

While looking at copy fails on collections.OrderedDict dataclass with required args · Issue #105736 · python/cpython · GitHub I encountered the following lines from OrderedDict._reduce

On the python versions I tested (3.10, 3.11) vars(OrderedDict()) is {} and OrderedDict is immutable, so this loop seems redundant. In the unit testing I cannot find a test covering this code path.

@rhettinger The vars(OrderedDict()) was introduced in Issue #11875: Alter the previous fix to work better with subclasses · python/cpython@d07eaf1 · GitHub, although the context is a bit different

Can the lines of code above be removed, or is there a reason why the lines are still there?

The __reduce__ code you’re seeing is in the pure Python implementation of OrderedDict. In that implementation, vars(OrderedDict()) has private attributes that need to be excluded from the results of __reduce__.

>>> vars(OrderedDict())
{'_OrderedDict__hardroot': <__main__._Link object at 0x105045d10>, '_OrderedDict__root': <weakproxy at 0x105045da0 to _Link at 0x105045d10>, '_OrderedDict__map': {}}

When you saw vars(OrderedDict()) returning {}, you were looking at the C version of OrderedDict which does not expose those private attributes. That is likely why you are confused.

In the unit testing I cannot find a test covering this code path.

The test case, PurePythonOrderedDictTests.test_reduce_not_too_fat, covers this code path. If you remove the pop loop, that test will fail.

Can the lines of code above be removed,

No

or is there a reason why the lines are still there?

Yes

1 Like