Pydantic: Enum field raises AttributeError or produces invalid schema with specific names

Created on 2 Dec 2019  路  4Comments  路  Source: samuelcolvin/pydantic

Bug

When calling BaseModel.schema() or BaseModel.schema_json()

An Enum field with the name regex raises an AttributeError.

An Enum field will produce an invalid schema if any of the following are used as an Enum name: gt; lt; ge; le; max_length; or multiple_of.

It looks like the Enum name is being interpreted as a ModelField property

Please complete:

  • OS: Ubuntu 18.04.3 LTS
  • Python version import sys; print(sys.version): 3.8.0 (default, Oct 28 2019, 16:14:01)
  • Pydantic version import pydantic; print(pydantic.VERSION): 1.2

Please read the docs and search through issues to
confirm your bug hasn't already been reported.

Where possible please include a self contained code snippet describing your bug:

import enum
import pydantic

class ExampleEnum(enum.Enum):
    just_a_value = "Just a normal value"

    # These names are interpreted as properties of the ModelField
    gt = "GT"
    lt = "LT"
    ge = "GE"
    le = "LE"
    max_length = "ML"
    multiple_of = "MO"

    # This name will cause an AttributeError (when uncommented)
    # regex = "RE"

class Example(pydantic.BaseModel):
    example: ExampleEnum

Example.schema()
...

The example above will produce this schema dict; where properties have been derived from the Enum names (rather than a Field model).

{'title': 'Example',
 'type': 'object',
 'properties': {'example': {'title': 'Example',
   'enum': ['Just a normal value', 'GT', 'LT', 'GE', 'LE', 'ML', 'MO'],
   'maxLength': <ExampleEnum.max_length: 'ML'>,
   'exclusiveMinimum': <ExampleEnum.gt: 'GT'>,
   'exclusiveMaximum': <ExampleEnum.lt: 'LT'>,
   'minimum': <ExampleEnum.ge: 'GE'>,
   'maximum': <ExampleEnum.le: 'LE'>,
   'multipleOf': <ExampleEnum.multiple_of: 'MO'>}},
 'required': ['example']}
bug

All 4 comments

Good catch, thank you for reporting.

PR welcome to fix this, an isinstance() check should suffice?

Otherwise I'll create a PR to fix this before the next minor release.

I'm working on a fix now.

see #1065

Amazing work, thank you :1st_place_medal:

(I only got as far as cloning the repo and creating an issue branch!)

sorry, should have let you work on it :pray:.

I started looking and found I had a solution.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iwoloschin picture iwoloschin  路  3Comments

ashpreetbedi picture ashpreetbedi  路  3Comments

sbv-trueenergy picture sbv-trueenergy  路  3Comments

samuelcolvin picture samuelcolvin  路  3Comments

krzysieqq picture krzysieqq  路  3Comments