Validación de datos con Pydantic

pip install pydantic

Pydantic vs Dataclasses vs clase regular de python

Clase regular de python

class Producto():
def __init__(self, titulo, descripcion, precio, publicado, id):
self.titulo = titulo
self.descripcion = descripcion
self.precio = precio
self.publicado = publicado
self.id = id

Python dataclase

from dataclasses import dataclass 
@dataclass
class Producto:
titulo: str
descripcion: str
precio: int
publicado: bool
id: int

Pydantic

from pydantic import BaseModel
from typing import Optional
from random import randrange

class Producto(BaseModel):
titulo: str
descripcion: str
precio: int
publicado: Optional[bool]= True
id: Optional[int]= None
dato = {
"titulo": "Xiaomi Mi 10T",
"descripcion": "Xiaomi",
"precio": 300,
"id": randrange(0, 100000000)
}
producto = Producto(**dato)

print(producto)

titulo='Xiaomi Mi 10T' descripcion='Xiaomi' precio=300 publicado=True id=59872935
  1. Getting started with Pydantic, a Python data validation library
  2. Pydantic — Better Data Validation for Python
  3. Documentación de Pydantic

--

--

Senior Python Developer, Software Architect, Big Data, Data Science, Machine Learning and Deep Learning, Debian SysAdmin, DevOps, Blogger and Freelancer.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ernesto Crespo

Ernesto Crespo

Senior Python Developer, Software Architect, Big Data, Data Science, Machine Learning and Deep Learning, Debian SysAdmin, DevOps, Blogger and Freelancer.