这是indexloc提供的服务,不要输入任何密码
Skip to content

arbitrary_types_allowed no longer works with root models in V2 #6710

@MarkusSintonen

Description

@MarkusSintonen

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

In V2 root models arbitrary_types_allowed no longer works. In V1 it used to work. Is it intended not to work anymore? Example below showing an use case that used to work in V1. I guess the issue is somehow related to generic models handling in V2.

Example Code

import numpy

from pydantic import BaseModel

try:
    from pydantic import ConfigDict, RootModel
    PYDANTIC_VERSION = "v2"
except ImportError:
    PYDANTIC_VERSION = "v1"


def test_arbitrary_root():
    if PYDANTIC_VERSION == 'v2':
        # Now it raises suggesting using arbitrary_types_allowed. But it is set!
        # Exception:
        # pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'numpy.ndarray'>.
        # Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.
        class MyNdarray(RootModel[numpy.ndarray]):
            model_config = ConfigDict(arbitrary_types_allowed=True)
            # defines deserialization of list to ndarray etc...
    else:
        # In v1 it works fine.
        class MyNdarray(BaseModel):
            __root__: numpy.ndarray

            class Config:
                arbitrary_types_allowed = True

            # defines deserialization of list to ndarray etc...

Python, Pydantic & OS Version

pydantic version: 2.0.3
        pydantic-core version: 2.3.0 release build profile
                 install path: /Users/markussintonen/Library/Caches/pypoetry/virtualenvs/leak-test-VvUvdXxD-py3.10/lib/python3.10/site-packages/pydantic
               python version: 3.10.12 (main, Jun 20 2023, 17:00:24) [Clang 14.0.3 (clang-1403.0.22.14.1)]
                     platform: macOS-13.4.1-x86_64-i386-64bit
     optional deps. installed: ['typing-extensions']

Selected Assignee: @lig

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions