Skip to content

Schema ignores enumerator on dictionary keys #4393

@lachlancoding

Description

@lachlancoding

Initial Checks

  • I have searched GitHub for a duplicate issue and I'm sure this is something new
  • I have searched Google & StackOverflow for a solution and couldn't find anything
  • I have read and followed the docs and still think this is a bug
  • I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like FastAPI or mypy)

Description

When a model has a dictionary field whose keys are of an Enumerated type, pydantic enforces validation of the dictionary keys at construction time, but the schema generated makes no mention of the key requirements.

A dictionary using a constr with a regex pattern for its keys will include its pattern in the 'patternProperties', but an enumerated type will just include the value type in the additionalProperties. Also, if the field is just a regular Enum, the valid values are included in the 'anyOf' field.

However in this specfic situation of an enum keyed dict, nothing is included in the schema, so someone trying to generate a valid example of the model would have no indication that there is even a requirement until it fails at construction time validation.

Example Code

from pydantic import BaseModel

class AnEnumerator(str, enum.Enum):
    a_value = "a"
    b_value = "other"

class BadType(BaseModel):
    an_enum_keyed_dict: Dict[AnEnumerator, int]

schema = BadType.schema()
print(schema)

{
  'title': 'BadType', 
  'type': 'object', 
  'properties': {
    'an_enum_keyed_dict': {
      'title': 'An Enum Keyed Dict', 
      'type': 'object', 
      'additionalProperties': {'type': 'integer'}
    }
  }, 
  'required': ['an_enum_keyed_dict']
}

Python, Pydantic & OS Version

pydantic version: 1.9.2
pydantic compiled: True
install path: /usr/local/lib/python3.8/dist-packages/pydantic
python version: 3.8.10 (default, Jun 22 2022, 20:18:18)  [GCC 9.4.0]
platform: Linux-5.15.0-46-generic-x86_64-with-glibc2.29
optional deps. installed: ['typing-extensions']

Affected Components

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions