skip to content

In Pydantic 2, how do you replace a version 1 model whose only field was __root__ holding a list, and what changes for its callers?

level: middleimportance: should knowfreq 25%

answer

  1. a dedicated generic class
  2. the value has a new attribute
  3. dumps the bare value
  4. iteration is not what you expect
  5. no class needed for a plain list

basics

~10 s

Subclass RootModel[list[Item]]: the value moves from root to .root, and validation and dumping take and return the bare list. A field named root now fails at class definition; TypeAdapter(list[Item]) suits lists needing no class.

solid answer

~40 s

Pydantic 2 refuses a field called `__root__`: defining one raises `PydanticUserError` telling you to use `pydantic.RootModel`. The replacement is `class ProductList(RootModel[list[ProductOut]])`. The value lives on `.root`; `ProductList.model_validate([...])` and `ProductList([...])` take the bare list, and `model_dump()` and `model_dump_json()` return a bare list. Callers that read `.__root__` must switch to `.root`, and iteration surprises people: a `RootModel` iterates like any model, yielding the pair `('root', value)`, so add `__iter__` and `__getitem__` if callers loop over or index it. `RootModel` refuses `model_config['extra']` and no longer supports `arbitrary_types_allowed`. When the list model existed only to validate and dump a list, `TypeAdapter(list[ProductOut])` replaces it with no class at all, and it also replaces version 1's `parse_obj_as`.

code

python · 28 lines
python
from pydantic import BaseModel, RootModel, TypeAdapter


class ProductOut(BaseModel):
    sku: str
    price: int


# was: class ProductList(BaseModel): __root__: List[ProductOut]
class ProductList(RootModel[list[ProductOut]]):
    def __iter__(self):
        return iter(self.root)

    def __getitem__(self, index: int) -> ProductOut:
        return self.root[index]


products = ProductList.model_validate([{'sku': 'A-1', 'price': '500'}])
print(products.root[0].sku, products[0].price, [p.sku for p in products])
#> A-1 500 ['A-1']
print(products.model_dump_json())
#> [{"sku":"A-1","price":500}]

# No class needed: validate and dump the list directly
product_list = TypeAdapter(list[ProductOut])
items = product_list.validate_python([{'sku': 'B-2', 'price': 9}])
print(product_list.dump_json(items))
#> b'[{"sku":"B-2","price":9}]'

go deeper

for a junior

Recall that a bare list or dict payload is modelled with RootModel[...] in Pydantic 2 and that the value lives on .root.

for a middle

Explain what callers see: bare-value validation and dumps, .root instead of root, and iteration yielding a ('root', value) pair unless you define iter.

for a senior

Show when to delete the class and use a TypeAdapter instead, and how to find callers that index or loop over the old model.

for a principal

Judge whether root models belong in the public types at all, or whether TypeAdapter keeps collection handling at the edges.

## What a custom root type is Most models describe a JSON object with named fields. Sometimes the payload is not an object at all: a bare list of products, or a dict keyed by SKU. Version 1 handled this with a magic field named `__root__`; the model wrapped that one value. Pydantic 2 replaced the magic field with a dedicated generic class, **`RootModel`**, and made the old spelling an error: a `BaseModel` that defines `__root__` raises `PydanticUserError` with the message "To define root models, use `pydantic.RootModel` rather than a field called '__root__'". ## Before and after ```python from typing import List from pydantic import BaseModel # version 1 class ProductList(BaseModel): __root__: List[ProductOut] products = ProductList.parse_obj(rows) first = products.__root__[0] ``` In Pydantic 2 the same type is `class ProductList(RootModel[list[ProductOut]])`, validated with `ProductList.model_validate(rows)` and read as `products.root[0]`. ## RootModel in practice - The root type is the **generic parameter**: `RootModel[list[ProductOut]]`, `RootModel[dict[str, int]]`. - You can use the parametrized class directly (`Skus = RootModel[list[str]]`) or subclass it to add methods. - The value is stored on **`.root`**, and it can be passed positionally: `ProductList([...])`, or as `root=`. - `model_validate`, `model_validate_json`, `model_dump`, `model_dump_json` and `model_json_schema` all work on the **bare value**: the JSON Schema of `RootModel[list[str]]` is an `array`, not an object. - Nested models inside the root still follow their own config, so an item model with `from_attributes=True` can be validated from ORM rows inside a list. ## What changes for callers | Caller does | Version 1 | Pydantic 2 | |---|---|---| | reads the value | `m.__root__` | `m.root` | | builds from a list | `ProductList(__root__=rows)` | `ProductList(rows)` | | validates a list | `ProductList.parse_obj(rows)` | `ProductList.model_validate(rows)` | | validates without a class | `parse_obj_as(List[ProductOut], rows)` | `TypeAdapter(list[ProductOut]).validate_python(rows)` | | loops over items | custom `__iter__` | still needs a custom `__iter__` | The last row is the usual surprise. `BaseModel.__iter__` yields `(field_name, value)` pairs, and `RootModel` inherits it, so `list(ProductList(rows))` is `[('root', [...])]`, not the products. Define `__iter__` and `__getitem__` on the subclass, delegating to `self.root`, if callers treat the model as a sequence. ## RootModel or TypeAdapter | Need | Choose | |---|---| | a named type other models nest as a field | `RootModel` subclass | | methods on the collection (`describe()`, totals) | `RootModel` subclass | | validate and dump a list in one function, no class | `TypeAdapter(list[ProductOut])` | | replace `parse_obj_as` or `schema_of` | `TypeAdapter` | `TypeAdapter` exposes `validate_python`, `validate_json`, `dump_python`, `dump_json` and `json_schema`, which covers what most version 1 root models were for. Build the adapter once and reuse it: constructing one analyses the type and builds a core schema, which has non-trivial overhead. ## Limits and gotchas - `RootModel` raises `PydanticUserError` if its config sets `extra`; there are no other fields to be extra. - `RootModel` types no longer support the `arbitrary_types_allowed` config setting. - Code that special-cased the `__root__` key in dumps or error locations needs a look, because the Pydantic 2 dump is the bare value. - A dict root works the same way: `RootModel[dict[str, str]]` validates and dumps the bare mapping, which suits payloads keyed by an ID. - `model_construct()` on a root model takes the root value positionally, skipping validation as it does for any model. ## Migrating the list model 1. Replace the `__root__` field with a `RootModel[...]` base, keeping the class name so imports survive. 2. Search for `.__root__` and switch every hit to `.root`. 3. Add `__iter__` and `__getitem__` if any caller loops over or indexes the model. 4. Where the class has no methods and nothing nests it, consider deleting it in favour of a module-level `TypeAdapter`.

  • Why does list(my_root_model) give one pair instead of the items in Pydantic 2?
    `RootModel` inherits `BaseModel.__iter__`, which yields `(field_name, value)` pairs, and a root model has exactly one field, `root`. So iteration yields `('root', [...])`. Define `__iter__` returning `iter(self.root)`, and `__getitem__` returning `self.root[index]`, on the subclass if callers treat it as a sequence.

  • A __root__ field still works in Pydantic 2, just with a deprecation warning
  • A RootModel dumps as a dict with a single root key
  • Looping over a RootModel yields its items without any extra code
  • TypeAdapter cannot validate a list of models that read from ORM objects

Assumes Pydantic 2 (checked on 2.14.0): RootModel replaced the version 1 __root__ field in 2.0, and TypeAdapter replaced parse_obj_as.