What is the best practice to type / type-narrow tuples or lists where the elements can be anything, but I don't care what they are? #11030
-
|
I'm writing a pydantic validator to conver a two-element tuple into a pydantic model with two named attributes. class MyModel(BaseModel):
foo: int # this type doesn't really matter for the example
bar: int
@model_validator(mode="before"):
@classmethod
def from_tuple(cls, value: Any) -> Any:
if not isinstance(value, tuple):
return value
# value is now tuple[Unknown, ...]
# any usage of value then creates an error
if len(value) == 2:
return {"foo": value[0], "bar": value[1]}
return valueI need to check that there are at least 2 elements (or I could wrap it in a try/except IndexError), but obviously that complains because it's a I could
I'm not a huge fan of any these, but it's not clear to me that there is a great way just with types. Am I missing anything? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
By default, pyright doesn't report any errors with the above code. I'm guessing that you've enabled strict-mode type checking? One option that you haven't listed above is to write your own user-defined type guard function using def is_tuple(val: object) -> TypeIs[tuple[Any, ...]]:
return isinstance(val, tuple) |
Beta Was this translation helpful? Give feedback.
By default, pyright doesn't report any errors with the above code. I'm guessing that you've enabled strict-mode type checking?
One option that you haven't listed above is to write your own user-defined type guard function using
TypeIs: