Skip to content

Can't generate schema when typing.Never is involved #1038

Closed as not planned
Closed as not planned
@nicoonoclaste

Description

@nicoonoclaste

pydantic fails to generate a schema for typing.Never; I ran into this in a model generic over a TypeVar whose bound involved Never.

Error encountered

pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for typing.Never. 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.

Test case

from pydantic import Field
from pydantic.dataclasses import dataclass
from typing import Generic, Never, TypeVar


T = TypeVar('T', None, Never)

@dataclass(frozen=True, kw_only=True)
class GenericConfig(Generic[T]):
    foo: str
    bar: str | T = Field(None)

ParsedConfig = GenericConfig[None]
ResolvedConfig = GenericConfig[Never]

Workarounds

In this particular case, removing the bounds on T works, but is highly undesirable: one could then instantiate things like GenericConfig[int] without type-checking error.

I attempted to provide the schema manually, but couldn't get that to work:

from pydantic_core import core_schema
from pydantic import GetPydanticSchema

from typing import Annotated, Never as _Never
Never = Annotated[
    _Never,
    GetPydanticSchema(
        lambda tp, handler: core_schema.no_info_after_validator_function(
                lambda _: False, handler(tp)
        )
    ),
]

I'm assuming the handler(tp) call is the problem, but I couldn't find a way to directly construct a CoreSchema.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions