Skip to content

Literal enum fields are stored as mix-in type instead of enum field when using parse_raw or parse_json #2166

@yobiscus

Description

@yobiscus

Checks

  • I added a descriptive title to this issue
  • I have searched (google, github) for similar issues and couldn't find anything
  • I have read and followed the docs and still think this feature/change is needed
  • After submitting this, I commit to one of:
    • Look through open issues and helped at least one other person
    • Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future
    • Implement a Pull Request for a confirmed bug

Feature Request

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.7.1
            pydantic compiled: True
                 install path: /home/user/project/.venv/lib/python3.8/site-packages/pydantic
               python version: 3.8.5 (default, Jul 28 2020, 12:59:40)  [GCC 9.3.0]
                     platform: Linux-5.4.0-53-generic-x86_64-with-glibc2.29
     optional deps. installed: ['typing-extensions']
import enum
from typing import Literal
from pydantic import BaseModel

class Bar(str, enum.Enum):
    FIZ = "fiz"
    FUZ = "fuz"

class Foo(BaseModel):
    bar: Bar
    barfiz: Literal[Bar.FIZ]

Foo.parse_raw('{"bar": "fiz", "barfiz": "fiz"}')
Foo.parse_obj({"bar": "fiz", "barfiz": "fiz"})
# both return: Foo(bar=<Bar.FIZ: 'fiz'>, barfiz='fiz')

# expected: Foo(bar=<Bar.FIZ: 'fiz'>, barfiz=<Bar.FIZ: 'fiz'>)

I was expecting that the Pydantic would store Bar.FIZ for the Literal[Bar.FIZ] field above, as opposed to storing a str type (the enum's mix-in type. Mypy flags Literal[Bar.FIZ] above as an enum field, so accessing value on the barfiz attribute, for example, is perfectly fine by Mypy's rules, but breaks during runtime.

I realize that mypy's support for Literal enum fields is relatively new, but they have interesting properties that I am looking to make use of (I would love to see this work with discriminated union types, for example).

Would you consider adding a Config field to enable this behaviour? Should this be flagged as a bug instead and targetted for a 2.0 release?

Possibly related bugs:

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