Skip to content

Commit

Permalink
Merge pull request #620 from yukinarit/feature/fix-render-tuple
Browse files Browse the repository at this point in the history
Fix render_tuple with coerce
  • Loading branch information
yukinarit authored Dec 9, 2024
2 parents 1562940 + b55ec71 commit b1acb5e
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 4 deletions.
4 changes: 3 additions & 1 deletion serde/de.py
Original file line number Diff line number Diff line change
Expand Up @@ -956,7 +956,9 @@ def primitive(self, arg: DeField[Any], suppress_coerce: bool = False) -> str:
if self.suppress_coerce and suppress_coerce:
return dat
else:
return f'coerce_object("{self.class_name}", "{arg.name}", {typ}, {dat})'
assert arg.name
escaped_arg_name = arg.name.replace('"', '\\"')
return f'coerce_object("{self.class_name}", "{escaped_arg_name}", {typ}, {dat})'

def c_tor(self, arg: DeField[Any]) -> str:
return f"{typename(arg.type)}({arg.data})"
Expand Down
4 changes: 3 additions & 1 deletion serde/se.py
Original file line number Diff line number Diff line change
Expand Up @@ -923,7 +923,9 @@ def primitive(self, arg: SeField[Any]) -> str:
if self.suppress_coerce:
return var
else:
return f'coerce_object("{self.class_name}", "{arg.name}", {typ}, {var})'
assert arg.name
escaped_arg_name = arg.name.replace('"', '\\"')
return f'coerce_object("{self.class_name}", "{escaped_arg_name}", {typ}, {var})'

def string(self, arg: SeField[Any]) -> str:
return f"str({arg.varname})"
Expand Down
4 changes: 2 additions & 2 deletions tests/test_de.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ class Foo:
pass

rendered = Renderer("foo").render(DeField(tuple[str, int, list[int], Foo], "d", datavar="data"))
rendered_str = 'coerce_object("None", "data["d"][0]", str, data["d"][0])'
rendered_int = 'coerce_object("None", "data["d"][1]", int, data["d"][1])'
rendered_str = 'coerce_object("None", "data[\\"d\\"][0]", str, data["d"][0])'
rendered_int = 'coerce_object("None", "data[\\"d\\"][1]", int, data["d"][1])'
rendered_lst = '[coerce_object("None", "v", int, v) for v in data["d"][2]]'
rendered_foo = f"Foo.__serde__.funcs['foo'](data=data[\"d\"][3], {kwargs})"
assert rendered == f"({rendered_str}, {rendered_int}, {rendered_lst}, {rendered_foo},)"
Expand Down
9 changes: 9 additions & 0 deletions tests/test_type_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,12 @@ class Nested:
assert p3.s.s == "100"
assert p3.f.f == 1000.0
assert p3.b.b

@serde.serde(type_check=serde.coerce)
class InnerTuple:
# Note: `foo` needs to be longer than 1 char, to properly test
# quote escaping
foo: tuple[float, float]

f = InnerTuple(foo=(1, 2))
assert f.foo == (1.0, 2.0)

0 comments on commit b1acb5e

Please sign in to comment.