cattrs
cattrs copied to clipboard
Cattrs serializer is not round-trip safe for type B | X (B is a built-in type) when value is not type B
cattrs version: 24.1.3
Hi cattrs team, The round-trip serialization of a union type in the following case is not guaranteed. It is clearly stated in the manual that built-in types are passed through during the serialization. However, the structuring with the same type hint fails. It seems to contradict the intuition that round-trip serialization of the same type should be invertible.
I am aware of the workaround of customizing either the restructuring or structuring for the built-in types. But it also seems to me that these can be handled internally by cattrs.
Thanks a lot.
@attrs.define
class B:
b: int
c = make_converter()
c.structure(c.unstructure(1, float| B), float | B)
# where float can be substituted by any built-in types.
Error:
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "<cattrs generated structure __main__.B>", line 5, in structure_B
| res['b'] = __c_structure_b(o['b'])
| TypeError: 'int' object is not subscriptable
| Structuring class B @ attribute b
+------------------------------------