From a74232e10105c18b7197ff29ee1a6d685b1a47b9 Mon Sep 17 00:00:00 2001 From: Eric Jolibois Date: Tue, 2 Mar 2021 13:09:31 +0100 Subject: [PATCH] fix: variable length tuples of compound types (#2421) --- changes/2416-PrettyWood.md | 1 + pydantic/fields.py | 1 + tests/test_edge_cases.py | 9 ++++++++- 3 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 changes/2416-PrettyWood.md diff --git a/changes/2416-PrettyWood.md b/changes/2416-PrettyWood.md new file mode 100644 index 0000000000..8be855a63a --- /dev/null +++ b/changes/2416-PrettyWood.md @@ -0,0 +1 @@ +Support properly variable length tuples of compound types diff --git a/pydantic/fields.py b/pydantic/fields.py index 7d0c2a3ead..69a292bbbe 100644 --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -538,6 +538,7 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) elif len(args) == 2 and args[1] is Ellipsis: # e.g. Tuple[int, ...] self.type_ = args[0] self.shape = SHAPE_TUPLE_ELLIPSIS + self.sub_fields = [self._create_sub_type(args[0], f'{self.name}_0')] elif args == ((),): # Tuple[()] means empty tuple self.shape = SHAPE_TUPLE self.type_ = Any diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py index 26e08140e8..2c4254b49a 100644 --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -203,12 +203,19 @@ class Model(BaseModel): empty_tuple: Tuple[()] simple_tuple: tuple = None tuple_of_different_types: Tuple[int, float, str, bool] = None + tuple_of_single_tuples: Tuple[Tuple[int], ...] = () - m = Model(empty_tuple=[], simple_tuple=[1, 2, 3, 4], tuple_of_different_types=[4, 3, 2, 1]) + m = Model( + empty_tuple=[], + simple_tuple=[1, 2, 3, 4], + tuple_of_different_types=[4, 3, 2, 1], + tuple_of_single_tuples=(('1',), (2,)), + ) assert m.dict() == { 'empty_tuple': (), 'simple_tuple': (1, 2, 3, 4), 'tuple_of_different_types': (4, 3.0, '2', True), + 'tuple_of_single_tuples': ((1,), (2,)), }