With a Pydantic V2 BaseModel, I'm trying to allow multiple data types to be input but are parsed to a specific type via @field_validator. For example:
from typing import Iterable
class Example(BaseModel):
my_string: str # Will always become str due to field_validator
@field_validator('my_string', mode='before')
@classmethod
def parse_my_string(cls, value: str | Iterable[str]) -> str: # Allow both str and Iterable[str]
if isinstance(value, str):
return value
else:
return ', '.join(value)
but now if I try to instantiate it with an Iterable, it (Pylance) gives me red squigglies:
Example(my_string=['A', 'B', 'C'])
Argument of type "list[str]" cannot be assigned to parameter "my_string" of type "str" in function "init" "list[str]" is incompatible with "str"
Pylance(reportArgumentType)
How can I make it look to the field_validator method for potential input types?
I would hope/expect that validators can be checked for potential input argument types.