pythonpydanticpydantic-v2pydantic-settings

Use `RootModel` as `BaseSettings`


I want to use a following model for my settings:

import pydantic
import pydantic_settings

class Clustered(pydantic.BaseModel):
    is_clustered: typing.Literal[True]
    server_name: str


class NonClustered(pydantic.BaseModel):
    is_clustered: typing.Literal[False] = False

# ???
Settings = pydantic_settings.RootSettings[Clustered | NonClustered]

But I cannot seem to figure out a way to do this, and multiple inheritance does not work:

>>> class Settings(pydantic_settings.BaseSettings, pydantic.RootModel[NonClustered | Clustered]): pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.12/site-packages/pydantic/_internal/_model_construction.py", line 117, in __new__
    cls: type[BaseModel] = super().__new__(mcs, cls_name, bases, namespace, **kwargs)  # type: ignore
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen abc>", line 106, in __new__
  File "/usr/local/lib/python3.12/site-packages/pydantic/root_model.py", line 50, in __init_subclass__
    raise PydanticUserError(
pydantic.errors.PydanticUserError: `RootModel` does not support setting `model_config['extra']`

Solution

  • This is not possible yet, follow https://github.com/pydantic/pydantic-settings/issues/200 for updates.