Pydantic - Convert "str" to "bool"

Asked

Viewed 57 times

1

Good afternoon, I would like to convert data directly by pydantic. I receive in "str" data "no", "yes", "na", no" ... which needs to be converted to "bool".

from pydantic import BaseModel
class Usuario(BaseModel):
    id: int
    nome: str
    ativo: bool
# Nota-se que tenho o ativo como sim, gostaria de saber sem tem como eu tratar isso direto no Pydantic.
# Na realidade recebo de diversas formas, mas gostaria de tratar diretamente no pydantic, mas não sei se tem como.
usuario_dados = {"id":1, "nome":"Eliton", "ativo":"Sim"} 

try:
    eliton = Usuario(**usuario_dados)
except ValidationError as e:
    print(e.json())
  • a very dirty way of doing this, but that if it’s not something professional could solve, would you put a if and check the first position of the str if it’s n attribute as false, if it’s s attribute as true

1 answer

0

Use the Developer validator:

from pydantic import BaseModel, ValidationError, validator


class Usuario(BaseModel):
    id: int
    nome: str
    ativo: str

    @validator('ativo')
    def converte_valores(cls, v):
        if v in ['Sim', 'sim']:
            return True
        if  v in ['Não', 'nao', 'na']:
            return False
        raise ValueError('valor nao valido')


usuario_dados = {"id":1, "nome":"Eliton", "ativo":"Sim"} 

try:
    eliton = Usuario(**usuario_dados)
    print(eliton)
except ValidationError as e:
    print(e.json())
  • You wouldn’t have to change the type of attribute data ativo for bool? I’ve never used Pydantic, but it seems strange to mark the attribute as str and the validator returns a boolean

  • I believe it is irrelevant to the purpose of the library, which is to validate data. Since the input is a string, then obviously the annotated type will be string, but if you think it is not clear you can rename the decorated function converte_valores with an even more explicit name or add docstrings. here is the documentation I based on: https://pydantic-docs.helpmanual.io/usage/validators/

  • Yes, I checked the documentation too. My point is that the code is saying that ativo is the type str but its validator returns bool, that is, its validator returns an invalid data. My question is whether the library accepts this, if it would not have to change the value in the Model. I don’t think that’s irrelevant because the documentation you linked says: validators should either Return the Parsed value.. That is, the return of the validator will be the value assigned to the attribute ativo.

  • Anyway, if the questioner wishes, he could use the function as a basis bool_validator() that the library uses for types bool and implement its own version.

  • I confused you with the author of the question. And as for your observation, vc tbm can answer the question by suggesting your solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.