[Python] Change the logic of custom type from extra types (PhoneNumber)

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    There is the PhoneNumber type to validate phone numbers:

    from pydantic import BaseModel

    from pydantic_extra_types.phone_numbers import PhoneNumber


    class User(BaseModel):
    name: str
    phone_number: PhoneNumber


    user = User(name='John', phone_number='+447911123456')
    print(user.phone_number)
    #> tel:+44-7911-123456


    I'm satisfied with it except the unwanted "tel:" prefix. I applied a trick like that:

    from pydantic import BaseModel

    from pydantic_extra_types.phone_numbers import PhoneNumber


    class User(BaseModel):
    name: str
    phone_number: PhoneNumber

    @model_validator(mode="after")
    def remove_prefix_from_phone(self) -> "User":
    if self.phone_number:
    self.phone_number = self.phone_number.removeprefix("tel:")
    return self


    user = User(name='John', phone_number='+447911123456')
    print(user.phone_number)
    #> +44-7911-123456


    But problem is that I convert the field into str and the PhoneNumber class is not even considered as str subtype unlike EmailStr for example. Seems like it a bad move and MyPy marks it as error as well - incompatible types in assignment (meanwhile, the validation logic is fine).
    Maybe I could do it smarter?

    I couldn't think of other options but it should be done within the Pydantic model for sure, because I load data from DB in a web-service and prefix would be exist in auto-generated response.

    Would be glad for any piece of advice!

    Continue reading...

Compartilhe esta Página