Skip to content

Commit

Permalink
fix: support empty tuple type
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Feb 4, 2021
1 parent 13a5c7d commit 42dd733
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
1 change: 1 addition & 0 deletions changes/2318-PrettyWood.md
@@ -0,0 +1 @@
support empty tuple type
10 changes: 7 additions & 3 deletions pydantic/fields.py
Expand Up @@ -449,18 +449,22 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity)

if issubclass(origin, Tuple): # type: ignore
# origin == Tuple without item type
if not get_args(self.type_):
args = get_args(self.type_)
if not args:
self.type_ = Any
self.shape = SHAPE_TUPLE_ELLIPSIS
else:
self.shape = SHAPE_TUPLE
self.sub_fields = []
for i, t in enumerate(get_args(self.type_)):
for i, t in enumerate(args):
if t is Ellipsis:
self.type_ = get_args(self.type_)[0]
self.shape = SHAPE_TUPLE_ELLIPSIS
return
self.sub_fields.append(self._create_sub_type(t, f'{self.name}_{i}'))
elif t == ():
self.type_ = Any
else:
self.sub_fields.append(self._create_sub_type(t, f'{self.name}_{i}'))
return

if issubclass(origin, List):
Expand Down
9 changes: 7 additions & 2 deletions tests/test_edge_cases.py
Expand Up @@ -194,11 +194,16 @@ class Model(BaseModel):

def test_tuple_more():
class Model(BaseModel):
empty_tuple: Tuple[()]
simple_tuple: tuple = None
tuple_of_different_types: Tuple[int, float, str, bool] = None

m = Model(simple_tuple=[1, 2, 3, 4], tuple_of_different_types=[4, 3, 2, 1])
assert m.dict() == {'simple_tuple': (1, 2, 3, 4), 'tuple_of_different_types': (4, 3.0, '2', True)}
m = Model(empty_tuple=[], simple_tuple=[1, 2, 3, 4], tuple_of_different_types=[4, 3, 2, 1])
assert m.dict() == {
'empty_tuple': (),
'simple_tuple': (1, 2, 3, 4),
'tuple_of_different_types': (4, 3.0, '2', True)
}


def test_tuple_length_error():
Expand Down

0 comments on commit 42dd733

Please sign in to comment.