0

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 :)

2
  • @tdelaney its always going to be mobile number only, i have added the format Commented Aug 23, 2022 at 0:27
  • @tdelaney how do i add a series of regex? can you provide an example? Commented Aug 23, 2022 at 0:29

1 Answer 1

1
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))
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for your answer, i am getting following error "TypeError: unsupported operand type(s) for |: 'type' and 'type' "
i also tried with "data: List[str or phone]" but its only validating the first datatype i.e. str,
@DmUser because you have an older version of python that does not support | Union
@DmUser when you do an or statement it does or logic and returns the first true element, which both are True, but str goes first. You must do Union. I changed the code to run on your version of python, try it out.
Hey, Thank you so so much, its working fine and i am unblocked now. Thanks again :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.