2

I have the following model in pydantic (Version 2.0.3)

from typing import Tuple
from pydantic import BaseModel

class Model(BaseModel):
    test_field: Tuple[int]

But when I enter

model = Model(test_field=(1,2))

I get as error:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "/Users/tobi/Documents/scraiber/z_legacy/fastapi_test_app/venv/lib/python3.10/site-packages/pydantic/main.py", line 150, in __init__
    __pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)
pydantic_core._pydantic_core.ValidationError: 1 validation error for Model
test_field
  Tuple should have at most 1 item after validation, not 2 [type=too_long, input_value=(1, 2), input_type=tuple]
    For further information visit https://errors.pydantic.dev/2.0.3/v/too_long

Do you know how I can fix that?

tobias
  • 501
  • 1
  • 6
  • 15

2 Answers2

3

Following @Tim Robert's Answer, the linked PR suggests using the Ellipsis ... is the syntax you're after!

https://github.com/pydantic/pydantic/pull/512/files

class Model(BaseModel):
    test_field: Tuple[int, ...]
>>> Model(test_field=(1,2))
Model(test_field=(1, 2))
ti7
  • 16,375
  • 6
  • 40
  • 68
  • Many thanks for it. Assume, for instance, I have 100 `int` in a tuple. Is there a more elegant way to do instead of the two you mentioned? – tobias Jul 25 '23 at 09:49
  • I think the general advice is "don't do that" and a lot of fields is probably a bad design .. but if you do have a lot of fields, consider a NamedTuple https://stackoverflow.com/a/44833864/4541045 (which at least annotates the values).. you'll have to either provide every field (`[int, int, int, int, int]`), create a custom Type with that many fields, or use `...` and an `@field_validator` to assert the length https://docs.pydantic.dev/latest/usage/validators/ – ti7 Jul 25 '23 at 15:28
  • 1
    That makes sense. Thanks for your input. :) – tobias Jul 25 '23 at 17:03
0

Variable-length tuples are not supported. There's a bug report about it. Sequence can be used as a workaround.

https://github.com/pydantic/pydantic/issues/495

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 1
    You missed the fact that this issue has been closed as fixed by [this commit](https://github.com/pydantic/pydantic/commit/fe72ba13f469377057112d2f301f52cd3b206467) a few years ago. Variable length tuples **are** supported. – Daniil Fajnberg Jul 25 '23 at 12:34