1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How do I do type checking before casting using pydantic?

Discussão em 'Python' iniciado por Stack, Outubro 3, 2024 às 10:52.

  1. Stack

    Stack Membro Participativo

    I created a class using the dataclass decorator of pydantic and I want to check the type of an argument before it becomes an attribute of the class. This is my code:

    from pydantic.dataclasses import dataclass
    from pydantic import validator

    @dataclass
    class Person(object):
    name: Optional[str] = None

    @validator('name')
    def name_must_be_str(cls, v):
    if type(v) is not str:
    raise TypeError("'name' must be str, not " + type(v).__name__)
    return v


    Now when I create an instance like person = Person(12), the argument becomes a string, too ('12'). How can I check the type before the instance casts the argument to a string?

    Continue reading...

Compartilhe esta Página