DmUser
DmUser

Reputation: 69

Parse list of strings with different types

I need to parse a list of strings where strings are heterogeneous type. Ex: {data : ["+91-8827222222", "int_val", "str_val", "+91-8827222223", "+91-8827222224"]}

i want to verify above list, but not able to get exact answer of my question anywhere, I followed few references but it didn't helped. Parse list of Pydantic classes from list of strings https://fastapi.tiangolo.com/fr/tutorial/body-nested-models/

I Need something like this,

class mobile_no(data):
# validation code

class UserData(BaseModel):
   data: List[mobile_no, str, int]

Will appreciate your help :)

Upvotes: 0

Views: 315

Answers (1)

Igor Dragushhak
Igor Dragushhak

Reputation: 637

from typing import List, Union
import pydantic
import re

class phone(str):

    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not isinstance(v, str):
            raise TypeError('string required')
        if not re.match(r'^\+\d{2}\-\d{10}$', v):
            raise ValueError('invalid phone format')
        return cls(v)

class UserData(pydantic.BaseModel):
    data: List[Union[phone,str]]

user_data = UserData(data=["+91-8827222222", "int_val", "str_val", "+91-8827222223", "+91-8827222224"])

for item in user_data.data:
    print(item, type(item), isinstance(item, phone), isinstance(item, str))

Upvotes: 1

Related Questions