Skip to content

Commit

Permalink
Make ReturnDict support dict union operators on Python 3.9 and later (e…
Browse files Browse the repository at this point in the history
  • Loading branch information
spookylukey authored and sigvef committed Dec 3, 2022
1 parent 271101b commit 3735de6
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
17 changes: 17 additions & 0 deletions rest_framework/utils/serializer_helpers.py
@@ -1,3 +1,4 @@
import sys
from collections import OrderedDict
from collections.abc import Mapping, MutableMapping

Expand Down Expand Up @@ -28,6 +29,22 @@ def __reduce__(self):
# but preserve the raw data.
return (dict, (dict(self),))

if sys.version_info >= (3, 9):
# These are basically copied from OrderedDict, with `serializer` added.
def __or__(self, other):
if not isinstance(other, dict):
return NotImplemented
new = self.__class__(self, serializer=self.serializer)
new.update(other)
return new

def __ror__(self, other):
if not isinstance(other, dict):
return NotImplemented
new = self.__class__(other, serializer=self.serializer)
new.update(self)
return new


class ReturnList(list):
"""
Expand Down
22 changes: 22 additions & 0 deletions tests/test_serializer.py
Expand Up @@ -740,3 +740,25 @@ class TestSerializer(A, B):
'f4': serializers.CharField,
'f5': serializers.CharField,
}


class Test8301Regression:
@pytest.mark.skipif(
sys.version_info < (3, 9),
reason="dictionary union operator requires Python 3.9 or higher",
)
def test_ReturnDict_merging(self):
# Serializer.data returns ReturnDict, this is essentially a test for that.

class TestSerializer(serializers.Serializer):
char = serializers.CharField()

s = TestSerializer(data={'char': 'x'})
assert s.is_valid()
assert s.data | {} == {'char': 'x'}
assert s.data | {'other': 'y'} == {'char': 'x', 'other': 'y'}
assert {} | s.data == {'char': 'x'}
assert {'other': 'y'} | s.data == {'char': 'x', 'other': 'y'}

assert (s.data | {}).__class__ == s.data.__class__
assert ({} | s.data).__class__ == s.data.__class__

0 comments on commit 3735de6

Please sign in to comment.