Zero Labs
Industry News / AI

An in-depth introduction to Pydantic: Making Your Python Type Hints Actually Do Something

Source · Towards AI By Aunkit Chaki

From the publisher’s feed, collected in the ZeroLabs newsroom.

An in-Depth Introduction to Pydantic: Making Your Python Type Hints Actually Do SomethingFrom your first data model to validating LLM outputs, and why type hints alone were never going to save you.If you have written Python for more than a few months, you have almost certainly written a function that looks something like this.def create_user(data): if "name" not in data: raise ValueError("name is required") if "age" not in data: raise ValueError("age is required") if not isinstance(data["age"], int): try: data["age"] = int(data["age"]) except ValueError: raise ValueError("age must be a number") if data["age"] raise ValueError("age cannot be negative") if "email" not in data or "@" not in data["email"]: raise ValueError("invalid email") # ... twenty more lines before we do anything useful return dataForty lines of defensive code before a single line of business logic. And you wrote it again, slightly differently, in the next module. And then a teammate wrote a third version that forgot the negative age check.This is the problem Pydantic solves. It has been downloaded well over a billion times a month on PyPi, and it quietly sits under FastAPI, LangChain, the OpenAI SDK, Hugging Face tooling, and most of the agent frameworks you have heard of. If you build anything in AI/ML today, you are already using it whether you realize it or not.In this article, let’s understand why Pydantic exists, what problem it solves, and how to use it properly. We will go from the very first model all the way to validators, serialization, settings management and the places where it shows up in LLM pipelines.If you are only interested in how we use Pydantic in AI and ML, scroll down to the “Where Pydantic shows up in AI and ML work” part later in this blog post, where we talk about structured outputs, tool use, and agent pipelines.The core problem: Python type hints are polite suggestionsPython has had type hints since 3.5. You write this:def get_user(user_id: int) -> dict: ...And then you call get_user("banana") and Python runs it happily. No error. No warning. Nothing.That is by design. Type hints in Python are annotations, not enforcement. They exist for your IDE, for your future self reading the code at 2 AM. At runtime, the interpreter completely ignores them.For code you fully control, that is usually fine. The problem starts the moment data crosses a boundary into your program from somewhere you do not control.Think about where your data actually comes from:JSON from a third party APIA YAML or .env config fileA form submission from a browserA row read out of a CSVA message pulled off a queueA JSON blob generated by an LLMEvery one of those is a place where the outside world hands you something and says “trust me, this is a user object”. It is a dict of unknown shape with values of unknown type, and it might be missing half the keys.This is what people call the trust boundary. Everything inside your program is code you wrote and can reason about. Everything crossing that line into your program is untrusted, unvalidated, and unshaped.Unstructed data to structered blocksPydantic sits exactly on that line. Its job is simple to state and surprisingly hard to do well: take whatever arrived, check it against a schema you declared using ordinary Python type hints, coerce it where sensible, reject it loudly where it is wrong, and hand you back a real Python object with guaranteed types.Once data passes through a Pydantic model, you stop writing if key in data. You stop writing isinstance checks. You just use the object.Your first modelAlmost everything in Pydantic starts with BaseModel, so lets be clear about what it actually is before we use it.BaseModel is just a class that Pydantic gives you, and you inherit from it. That is the whole mechanic. But the moment you write class User(BaseModel), something useful happens: Pydantic reads your class body, looks at the type hints you wrote, and builds a validator out of them right there at import time. Your class walks away with a constructor that checks its inputs, a readable __repr__, working equality comparison, and methods to convert itself to and from dicts and JSON.So when you see BaseModel in the examples below, read it as "make this class validate itself".Here is the whole idea in eight lines.from pydantic import BaseModelclass User(BaseModel): id: int name: str email: str is_active: bool = Trueuser = User(id=101, name="Aunkit", email="xyz@ironmaiden.com")print(user)# OUTPUT: id=101 name='Aunkit' email='xyz@ironmaiden.com' is_active=TrueWe did not write a validation function. We did not write __init__. We did not write __repr__ or __eq__. We wrote four type hints, inherited from BaseModel, and got all of it for free.is_active: bool = True has a default, so it is optional. The other three have no default, so they are required.Now watch what happens when the data is a bit messy.user = User(id="101", name="Aunkit", email="aunkit@example.com")print(user.id, type(user.id))# OUTPUT: 101 We passed the string "101" and got back the integer 101. This is coercion, and it is one of the most useful things Pydantic does. Query parameters arrive as strings. Environment variables arrive as strings. CSV cells arrive as strings. Pydantic does the sensible conversion so you do not have to sprinkle int() calls everywhere.But coercion is not magic, and it is not permissive. It converts what can be meaningfully converted and refuses what cannot.User(id="101abc", name="Aunkit", email="aunkit@example.com")# OUTPUT: ValidationError: Input should be a valid integer,# unable to parse string as an integerThat is the important distinction. "101" is an integer written as text. "101abc" is not an integer at all. Pydantic knows the difference.Errors that actually tell you what went wrongValidation is only half the value. The other half is what happens when validation fails.from pydantic import ValidationErrortry: User(id="abc", name="Aunkit")except ValidationError as e: print(e.errors())[ { 'type': 'int_parsing', 'loc': ('id',), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'abc' }, { 'type': 'missing', 'loc': ('email',), 'msg': 'Field required', 'input': {'id': 'abc', 'name': 'Aunkit'} }]Two things worth pointing out here.First, Pydantic collected all the errors, not just the first one. Handwritten validation almost always bails on the first problem, which means your user fixes one field, resubmits, and discovers a second problem. Pydantic tells you everything that is wrong in one pass.Second, look at loc. That is the path to the field that failed. For a flat model it is boring, but for a deeply nested one it becomes ('company', 'address', 'pincode') and it will save you a genuine amount of debugging time.And because errors() returns structured data and not a formatted string, you can turn it straight into an API response, a log entry, or a retry prompt for an LLM. We will come back to that last one.Constraints with FieldType checking gets you far, but real data has rules that go beyond types. An age is an int, sure, but it is also not negative and not 900. A username is a str, but it is not an empty string.That is what Field is for.from pydantic import BaseModel, Field, EmailStrclass User(BaseModel): id: int = Field(gt=0, description="Primary key, always positive") name: str = Field(min_length=2, max_length=50) email: EmailStr age: int = Field(default=18, ge=13, le=120) bio: str | None = Field(default=None, max_length=500) tags: list[str] = Field(default_factory=list)The constraint names are worth memorizing because you will use them constantly:gt, ge, lt, le numeric bounds (greater than, greater or equal, and so on)min_length, max_length strings, lists, dictspattern regex for stringsmultiple_of numeric divisibilityThe constraint names are worth memorizing because you will use them constantly:gt and ge set a lower bound on numbers (greater than, greater than or equal to)lt and le set an upper bound (less than, less than or equal to)min_length and max_length work on anything with a length, so strings, lists, sets, and dictspattern takes a regex that a string must matchmultiple_of requires a number to divide evenly, which is handy for things like page sizes or batch countsThere are a few more (max_digits and decimal_places for Decimal, allow_inf_nan for floats), but the five above cover almost everything you will actually reach for.Two details I would like to call outEmailStr is one of Pydantic's built in types that actually validates the format rather than just checking it is a string. There is a family of these: HttpUrl, IPvAnyAddress, PositiveInt, SecretStr, UUID4, PastDate, and more. SecretStr in particular is nice for API keys, because it masks the value in reprs and logs so you do not accidentally leak a key into stdout.tags: list[str] = Field(default_factory=list) is the fix for Python's classic mutable default argument bug. If you wrote tags: list[str] = [], in plain Python every instance would share the same list. Pydantic actually protects you here even if you write it the naive way, but default_factory is the habit worth building because it makes the intent explicit and works for any mutable default.There is also a second way to write constraints, using Annotated, and you will see it a lot in modern codebases:from typing import Annotatedfrom pydantic import BaseModel, FieldScore = Annotated[int, Field(ge=0, le=100)]class Result(BaseModel): math: Score physics: Score chemistry: ScoreThe advantage is that the constraint becomes a reusable named type. Define Score once, use it everywhere, change the bounds in one place.Nesting: where it starts to pay offA flat model is a nice demo. Real data is nested, and this is where Pydantic goes from convenient to genuinely load bearing.from pydantic import BaseModel, Fieldclass Address(BaseModel): street: str city: str pincode: str = Field(pattern=r"^\d{6}$")class Company(BaseModel): name: str address: Addressclass Employee(BaseModel): name: str company: Company skills: list[str]Now hand it a raw nested dict, exactly the kind of thing you get back from an API call.raw = { "name": "Aunkit", "company": { "name": "PayPal", "address": { "street": "Sarjapur Road", "city": "Bangalore", "pincode": "569901" } }, "skills": ["Python", "ML", "SQL"]}emp = Employee(**raw)print(emp.company.address.city)# OUTPUT: BangalorePydantic walked the entire tree, validated every level, and built real Address and Company objects out of the nested dicts. You now get autocomplete on emp.company.address.city. You did not write a single line of parsing code.And if something deep inside is wrong, you get told exactly where:raw["company"]["address"]["pincode"] = "56990" # only five digitsEmployee(**raw)# OUTPUT: # ValidationError: 1 validation error for Employee# company.address.pincode# String should match pattern '^\d{6}$'Custom validators: rules that types cannot expressConstraints handle “this number must be positive”. They cannot handle “this username must not be on the banned list” or “the end date must be after the start date”. For that you write validators.There are two kinds, and the distinction is important.Field validators run on a single field. Model validators run on the whole model and can see every field at once.Here is both, in one model.from pydantic import BaseModel, field_validator, model_validatorclass Signup(BaseModel): username: str password: str confirm_password: str @field_validator("username") @classmethod def username_must_be_alphanumeric(cls, v: str) -> str: if not v.isalnum(): raise ValueError("username must be alphanumeric") return v.lower() @model_validator(mode="after") def passwords_must_match(self): if self.password != self.confirm_password: raise ValueError("passwords do not match") return selfThe passwords_must_match check is impossible to express as a field validator, because a field validator only ever sees one value. It needs to compare two fields, so it has to be a model validator.Three rules to internalize about validators:They must return the value. A validator that checks something and forgets to return v will silently set your field to None. This is the single most common Pydantic bug I see.Raise ValueError, not ValidationError. Pydantic catches your ValueError and wraps it into a proper ValidationError with the field path attached. If you raise ValidationError yourself you break that machinery.Field validators need @classmethod, and it goes below @field_validator. Order matters.before vs afterBoth decorators take a mode argument, and this is where validators become genuinely powerful.mode="after" (the default) runs after Pydantic has already coerced and type checked the value. You get a clean, correctly typed value and you apply business rules to it.mode="before" runs on the raw input, before any type checking. You get whatever the outside world sent, and you can reshape it into something Pydantic can then validate normally.That second one is what you will mostly find in real world data usecases.from pydantic import BaseModel, field_validatorclass Article(BaseModel): title: str tags: list[str]@field_validator("tags", mode="before") @classmethod def split_comma_separated(cls, v): if isinstance(v, str): return [t.strip() for t in v.split(",") if t.strip()] return va = Article(title="Pydantic 101", tags="python, validation, ml")print(a.tags)# OUTPUT: ['python', 'validation', 'ml']Some upstream system sends tags as a comma separated string. Rather than cleaning it up at every call site, you clean it once, inside the model, and every consumer of Article gets a proper list.The way i think of this is: a before validator reshapes, an after validator enforces.Everything in the middle orange box, the part doing the actual heavy lifting, is written in Rust. That is the headline change in Pydantic v2. The validation core was rewritten and moved out of Python entirely, which is why v2 is dramatically faster than v1 despite doing more work.Computed fieldsSometimes a value is derived rather than supplied. You do not want the caller passing it in, but you do want it to show up when you serialize.from pydantic import BaseModel, computed_fieldclass Rectangle(BaseModel): width: float height: float @computed_field @property def area(self) -> float: return self.width * self.heightr = Rectangle(width=3, height=4)print(r.area)# OUTPUT: 12.0print(r.model_dump())# OUTPUT: {'width': 3.0, 'height': 4.0, 'area': 12.0}Serialization: the trip back outValidation gets data in. Serialization gets it back out. Pydantic gives you both directions with a small, consistent set of methods.user = User(id=1, name="Aunkit", email="aunkit@example.com")user.model_dump() # -> Python dictuser.model_dump(mode="json") # -> dict with JSON safe valuesuser.model_dump_json(indent=2) # -> JSON stringuser.model_dump(exclude={"email"}) # -> drop specific fieldsuser.model_dump(exclude_none=True) # -> drop fields that are NoneAnd going the other way:User.model_validate(some_dict) # from a dictUser.model_validate_json(raw_json) # straight from a JSON stringmodel_validate_json is worth calling out. It parses and validates in one step, inside the Rust core, without building an intermediate Python dict. For large payloads that is meaningfully faster than json.loads() followed by model_validate().The difference between model_dump() and model_dump(mode="json") catches people out. Plain model_dump() keeps Python native objects, so a datetime stays a datetime and a UUID stays a UUID. With mode="json" those become strings, which is what you want before handing it to json.dumps or a web framework.Configuration with ConfigDictYou have seen model_config a couple of times now. It is how you change a model's behaviour, and there are a handful of settings worth knowing by name.from pydantic import BaseModel, ConfigDictclass StrictModel(BaseModel): model_config = ConfigDict( strict=True, # no type coercion at all extra="forbid", # reject unknown fields frozen=True, # immutable after creation validate_assignment=True, # re-validate on attribute assignment str_strip_whitespace=True # auto strip strings )Two of these deserve real attention.extra="forbid" changes a default that surprises people. By default, Pydantic ignores fields it does not recognize. If an API sends you {"name": "x", "nmae": "y"}, that typo is silently dropped and you never find out. With extra="forbid", it raises. For internal contracts where you control both sides, forbid is usually the right call. For third party APIs that add fields over time, the default ignore behavior is what keeps your code from breaking on someone else's release day.validate_assignment=True fixes another default that trips people up. Out of the box, Pydantic validates at construction time only. After that, user.age = "banana" will happily go through. Turn this on and assignments get validated too. It costs a little performance, so it is opt in rather than default.Where Pydantic shows up in AI and ML workEverything so far applies to any Python project. This section is the part that makes Pydantic worth learning properly if you build models and pipelines rather than web apps.The common thread is that machine learning systems are full of boundaries. Between your feature pipeline and your model. Between your model and whatever calls it. Between an LLM’s text output and the code that has to act on it. Between one agent and the next. Every one of those is a place where assumptions go unchecked until something breaks in production, and every one of them is a place a Pydantic model belongs.Structured outputs from LLMsLLMs return text. You want objects. The gap between those two things is where a lot of production AI code goes to die.Pydantic closes it from both ends. It generates the schema you send to the model, and it validates the response that comes back.from typing import Literalfrom pydantic import BaseModel, Fieldclass MovieReview(BaseModel): title: str sentiment: Literal["positive", "negative", "neutral"] rating: int = Field(ge=1, le=10) themes: list[str] = Field(max_length=5) spoilers: boolprint(MovieReview.model_json_schema())model_json_schema() emits a standard JSON Schema document. That is exactly the format that OpenAI's structured outputs, Anthropic's tool use, and Google's function calling all expect. You define the shape once, in Python, and the schema falls out for free. No maintaining a JSON blob that drifts out of sync with your parsing code. Most provider SDKs now accept the model class directly and handle the schema conversion for you.I would like to make a thing clear here. When you send a schema to an LLM provider, the model is told the shape of the output but it does not respect every rule in your schema equally.Take sentiment: Literal["positive", "negative", "neutral"]. Literal is Python's way of saying "this field can only be one of these exact values". The provider turns that into a fixed list of options, and the model genuinely cannot pick anything outside it. Field names, nesting, and basic types like int and str are respected the same way.Numeric ranges and regex patterns are a different story. Field(ge=1, le=10) on the rating tells Pydantic to reject anything outside 1 to 10, but most providers ignore that rule when generating, so the model can still return a 47. A pattern regex will almost never be enforced on the model's side.That does not make the constraints useless. It means you have two layers rather than one. The schema shapes what the model tries to produce, and Pydantic enforces what your code will actually accept. The model might hand you a rating of 47. Your Field(ge=1, le=10) is what stops it reaching your database.The retry loopWhich brings us to the pattern that makes all of this practical.from pydantic import ValidationErrordef get_review(prompt: str, max_attempts: int = 3) -> MovieReview: for attempt in range(max_attempts): raw = call_llm(prompt) try: return MovieReview.model_validate_json(raw) except ValidationError as e: prompt += f"\n\nYour previous output was invalid:\n{e}\nReturn corrected JSON only." raise RuntimeError(f"Model failed validation after {max_attempts} attempts")This is the whole reason structured error messages matter. Pydantic’s error text is descriptive enough to hand straight back to the model, and it usually corrects itself on the first retry. “Input should be less than or equal to 10” is a genuinely actionable instruction for an LLM in a way that a stack trace never would be.Agent tools and function callingEvery agent framework needs to tell the model what tools exist and what arguments they take. That description is a JSON schema and the cleanest way to produce one is a Pydantic modelclass SearchDatabase(BaseModel): """Search the product catalog by keyword.""" query: str = Field(description="Search terms") limit: int = Field(default=10, ge=1, le=100) category: Literal["electronics", "books", "clothing"] | None = NoneThe docstring becomes the tool description. The Field(description=...) values become per argument descriptions. The Literal becomes an enum the model is constrained to. All of it flows into the schema automatically, and the arguments get validated before your function ever runs.That last point is the one people underrate. Your tool function receives a validated SearchDatabase instance, not a dict the model made up. limit is an int between 1 and 100, guaranteed, so the function body has no defensive code in it at all.Routing agent actions with discriminated unionsOnce an agent can do more than one thing, you need to parse an output that could be any of several shapes. The naive approach is to look for a key, branch on it and parse manually. Pydantic has a proper mechansim for this and it is one of the most useful features for agent work specially.from typing import Annotated, Literal, Unionfrom pydantic import BaseModel, Field, TypeAdapterclass SearchWeb(BaseModel): action: Literal["search_web"] query: strclass RunSQL(BaseModel): action: Literal["run_sql"] table: str limit: int = Field(default=100, le=1000)class Respond(BaseModel): action: Literal["respond"] message: strAgentAction = Annotated[ Union[SearchWeb, RunSQL, Respond], Field(discriminator="action")]adapter = TypeAdapter(AgentAction)step = adapter.validate_json(llm_output)The discriminator tells Pydantic to read the action field first and then validate against only that one model. Without it, Pydantic would try each member of the union in turn and give you a confusing error listing every failure. With it, you get a precise error against the right shape, and it is faster because there is no trial and error.On the other side, step is now correctly typed. If you write if isinstance(step, RunSQL), your editor knows step.table exists inside that branch. Agent code that would otherwise be a pile of dictionary lookups becomes something you can actually navigate.Contracts between pipeline stagesRAG pipelines and feature pipelines have the same underlying problem: a chain of steps, each one trusting whatever the last one produced. Weeks later, someone changes the chunker to emit a page field instead of page_number, retrieval silently degrades, and nobody notices until quality metrics drift.Define the contract once and validate at the seam.from pydantic import BaseModel, Field, HttpUrlclass Chunk(BaseModel): doc_id: str chunk_index: int = Field(ge=0) text: str = Field(min_length=1) source_url: HttpUrl token_count: int = Field(gt=0, le=8192) embedding_model: strNow an empty chunk cannot get embedded, a chunk too long for the encoder fails loudly at ingest time rather than producing a truncated vector, and every record carries the embedding model that produced it, so you know exactly which chunks need reprocessing when you upgrade encoders. That last field costs you nothing today and saves you a full reindex you cannot reason about later.Experiment configurationReproducibility is mostly a configuration problem. If a training run’s hyperparameters live in a mix of argparse flags, environment variables, and hardcoded constants, reconstructing a run from three months ago is archaeology.from typing import Literalfrom pydantic import Fieldfrom pydantic_settings import BaseSettings, SettingsConfigDictclass TrainConfig(BaseSettings): model_config = SettingsConfigDict(env_file=".env", env_prefix="TRAIN_") learning_rate: float = Field(default=3e-4, gt=0, lt=1) batch_size: int = Field(default=32, ge=1) epochs: int = Field(default=10, ge=1) optimizer: Literal["adam", "adamw", "sgd"] = "adamw" seed: int = 42 dropout: float = Field(default=0.1, ge=0.0, lt=1.0)cfg = TrainConfig()run_metadata = cfg.model_dump() # log this alongside your metricsOne object holds the entire configuration, bounds checked at startup so a typo in a learning rate fails before you burn an hour of GPU time. model_dump() gives you a dict you can log to MLflow or Weights and Biases in one line, and TrainConfig.model_validate(logged_dict) reconstructs it exactly when you want to rerun.LLM as a JudgeIf you use an LLM to grade outputs, the grader’s response needs the same discipline as anything else. An eval that silently fails to parse a verdict and defaults to passing is worse than no eval.from typing import Literalfrom pydantic import BaseModel, Fieldclass JudgeVerdict(BaseModel): score: int = Field(ge=1, le=5) reasoning: str = Field(min_length=20) failure_mode: Literal["hallucination", "incomplete", "off_topic", "none"]The min_length=20 on reasoning is a small thing that matters. Judge models will happily return a one word justification if you let them, and forcing a real explanation both improves the grading quality and gives you something to read when you audit disagreements.One thing Pydantic will not do for youArrays. Pydantic has no native understanding of a numpy array or a torch tensor, and if you annotate a field with one you will get an error telling you the type is not supported.The quick fix is to tell Pydantic to accept it as an opaque object:import numpy as npfrom pydantic import BaseModel, ConfigDictclass Batch(BaseModel): model_config = ConfigDict(arbitrary_types_allowed=True) features: np.ndarray batch_id: strBe clear about what this buys you, though. It performs an isinstance check and nothing more. Shape, dtype, and NaN content are all unchecked, and the model will not serialize to JSON without a custom serializer.For anything more than that, the honest answer is that Pydantic is the wrong layer. Validate the metadata around your arrays with Pydantic, and validate the arrays themselves with something built for it.ConclusionWe started with a simple problem: Python type hints are ignored at runtime, and real data arrives from places you do not control. Everything after that was one idea applied in different places. Declare the shape once, let Pydantic enforce it, and stop writing defensive code downstream.The part that matters most if you work in AI is the last stretch. Pydantic is what turns an LLM’s text output into a typed object you can build on. Schema generation on the way out, validation on the way back, error messages good enough to hand to the model as a retry. That loop sits under most of the agent tooling being written today, and it is worth understanding before you reach for a framework that wraps it.The takeaway is small enough to remember. Draw a line around your program. Everything crossing that line gets validated. Everything inside it can be trusted.Hope you liked this explanation of mine. If you like this work, please consider upvoting!Feel free to reach out on linkedin if you have any questions.Happy Learning!Aunkit ChakiEmail: chaki18081999@gmail.comLinkedIn: https://www.linkedin.com/in/aunkit-chaki-38807b174/ResourcesPydantic documentation: https://docs.pydantic.dev/Pydantic GitHub: https://github.com/pydantic/pydanticpydantic-settings: https://docs.pydantic.dev/latest/concepts/pydantic_settings/Migration guide from v1 to v2: https://docs.pydantic.dev/latest/migration/An in-depth introduction to Pydantic: Making Your Python Type Hints Actually Do Something was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.