@@ -150,24 +150,47 @@ def test_exclude_none():
150150
151151
152152def test_exclude_default ():
153+ class TestComparison :
154+ def __init__ (self , val : Any ):
155+ self .val = val
156+
157+ def __eq__ (self , other ):
158+ return self .val == other .val
159+
153160 v = SchemaSerializer (
154161 core_schema .typed_dict_schema (
155162 {
156163 'foo' : core_schema .typed_dict_field (core_schema .nullable_schema (core_schema .int_schema ())),
157164 'bar' : core_schema .typed_dict_field (
158165 core_schema .with_default_schema (core_schema .bytes_schema (), default = b'[default]' )
159166 ),
167+ 'foobar' : core_schema .typed_dict_field (
168+ core_schema .with_default_schema (
169+ core_schema .any_schema (),
170+ default = TestComparison (val = 1 ),
171+ default_comparison = lambda value , default : value .val == - 1 * default .val ,
172+ )
173+ ),
160174 }
161175 )
162176 )
163177 assert v .to_python ({'foo' : 1 , 'bar' : b'x' }) == {'foo' : 1 , 'bar' : b'x' }
164178 assert v .to_python ({'foo' : 1 , 'bar' : b'[default]' }) == {'foo' : 1 , 'bar' : b'[default]' }
165179 assert v .to_python ({'foo' : 1 , 'bar' : b'[default]' }, exclude_defaults = True ) == {'foo' : 1 }
166180 assert v .to_python ({'foo' : 1 , 'bar' : b'[default]' }, mode = 'json' ) == {'foo' : 1 , 'bar' : '[default]' }
167- assert v .to_python ({'foo' : 1 , 'bar' : b'[default]' }, exclude_defaults = True , mode = 'json' ) == {'foo' : 1 }
168-
169181 assert v .to_json ({'foo' : 1 , 'bar' : b'[default]' }) == b'{"foo":1,"bar":"[default]"}'
170182 assert v .to_json ({'foo' : 1 , 'bar' : b'[default]' }, exclude_defaults = True ) == b'{"foo":1}'
183+ # Note that due to the custom comparison operator foobar must be excluded
184+ assert v .to_python ({'foo' : 1 , 'bar' : b'x' , 'foobar' : TestComparison (val = - 1 )}, exclude_defaults = True ) == {
185+ 'foo' : 1 ,
186+ 'bar' : b'x' ,
187+ }
188+ # foobar here must be included
189+ assert v .to_python ({'foo' : 1 , 'bar' : b'x' , 'foobar' : TestComparison (val = 1 )}, exclude_defaults = True ) == {
190+ 'foo' : 1 ,
191+ 'bar' : b'x' ,
192+ 'foobar' : TestComparison (val = 1 ),
193+ }
171194
172195
173196def test_function_plain_field_serializer_to_python ():
0 commit comments