Created
March 30, 2021 07:20
-
-
Save anatoly-scherbakov/9238dd53ad7aabeacf3a5170558d3659 to your computer and use it in GitHub Desktop.
Cannot generate JSON Schema for a model with generic class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import Enum | |
from typing import Optional, Generic, TypeVar, Set | |
from pydantic import BaseModel, version | |
from pydantic.fields import ModelField | |
from pydantic.schema import model_schema | |
ContainerType = TypeVar('ContainerType') | |
class Color(str, Enum): | |
"""Cat colors.""" | |
RED = 'red' | |
WHITE = 'white' | |
BLACK = 'black' | |
class CommaSeparated(Generic[ContainerType]): | |
"""Comma separated values of a container.""" | |
@classmethod | |
def __get_validators__(cls): | |
"""Ensure pydantic compatibility.""" | |
yield cls.validate | |
@classmethod | |
def validate(cls, raw_value: str, field: ModelField) -> ContainerType: | |
"""Validate the raw value.""" | |
raise ValueError( | |
'I will write this validation later, too lazy right now :(', | |
) | |
class CatsQuery(BaseModel): | |
"""Query our cats herd.""" | |
color__in: Optional[CommaSeparated[Set[Color]]] = None | |
print(f'Pydantic version: {version.VERSION}') | |
model_schema(CatsQuery) | |
''' | |
Output: | |
Pydantic version: 1.7.3 | |
tests/test_comma_separated_query_strings.py:None (tests/test_comma_separated_query_strings.py) | |
test_comma_separated_query_strings.py:42: in <module> | |
model_schema(CatsQuery) | |
../venv/lib/python3.8/site-packages/pydantic/schema.py:153: in model_schema | |
m_schema, m_definitions, nested_models = model_process_schema( | |
../venv/lib/python3.8/site-packages/pydantic/schema.py:525: in model_process_schema | |
m_schema, m_definitions, nested_models = model_type_schema( | |
../venv/lib/python3.8/site-packages/pydantic/schema.py:566: in model_type_schema | |
f_schema, f_definitions, f_nested_models = field_schema( | |
../venv/lib/python3.8/site-packages/pydantic/schema.py:222: in field_schema | |
f_schema, f_definitions, f_nested_models = field_type_schema( | |
../venv/lib/python3.8/site-packages/pydantic/schema.py:475: in field_type_schema | |
assert field.shape == SHAPE_SINGLETON, field.shape | |
E AssertionError: 10 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment