Skip to content

Commit 8070dac

Browse files
authored
Add None to the PlainDatatypeConverter (#67)
* Add None to the PlainDatatypeConverter * Add changelog * use type(None) instead
1 parent 572c79c commit 8070dac

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

.changelog/_unreleased.toml

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
[[entries]]
2+
id = "0240153b-1aaa-4801-b258-522c608bb936"
3+
type = "improvement"
4+
description = "Add None to the set of plain datatypes that can be de/serialized"
5+
author = "@rhaps0dy"

databind/src/databind/json/converters.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,7 @@ def convert(self, ctx: Context) -> t.Any:
373373

374374

375375
class PlainDatatypeConverter(Converter):
376-
"""A converter for the plain datatypes #bool, #bytes, #int, #str and #float.
376+
"""A converter for the plain datatypes #bool, #bytes, #int, #str, #float and #null.
377377
378378
Arguments:
379379
direction (Direction): The direction in which to convert (serialize or deserialize).
@@ -394,6 +394,7 @@ class PlainDatatypeConverter(Converter):
394394
(int, float): float,
395395
(float, int): _int_lossless,
396396
(bool, bool): bool,
397+
(type(None), type(None)): lambda x: x,
397398
}
398399

399400
# Used only during deserialization if the #fieldinfo.strict is disabled.
@@ -406,6 +407,7 @@ class PlainDatatypeConverter(Converter):
406407
(int, str): str,
407408
(float, str): str,
408409
(bool, str): str,
410+
(type(None), type(None)): lambda x: x,
409411
}
410412
)
411413

@@ -428,7 +430,6 @@ def convert(self, ctx: Context) -> t.Any:
428430
)
429431
adapters = self._strict_adapters if strict.enabled else self._nonstrict_adapters
430432
adapter = adapters.get((source_type, target_type))
431-
432433
if adapter is None:
433434
raise ConversionError.expected(self, ctx, target_type, source_type)
434435

databind/src/databind/json/tests/converters_test.py

+4
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ def test_plain_datatype_converter(direction: Direction) -> None:
7878
with pytest.raises(ConversionError):
7979
mapper.convert(direction, "foobar", int)
8080

81+
# None should behave the same in both cases
82+
assert mapper.convert(direction, None, type(None)) is None
83+
assert mapper.convert(direction, None, None) is None
84+
8185

8286
@pytest.mark.parametrize("direction", (Direction.SERIALIZE, Direction.DESERIALIZE))
8387
def test_decimal_converter(direction: Direction) -> None:

0 commit comments

Comments
 (0)