Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encode enums as typing.Literal instead of Enum class #356

Open
FeherMarcell opened this issue Jun 9, 2023 · 0 comments
Open

Encode enums as typing.Literal instead of Enum class #356

FeherMarcell opened this issue Jun 9, 2023 · 0 comments

Comments

@FeherMarcell
Copy link

FeherMarcell commented Jun 9, 2023

When only specific values are allowed for a property in OpenAPI, they are listed as an enum, which is translated to an Enum class in the generated Python model. Unfortunately, when the model is converted to a dictionary using the Pydantic built-in model.dict() method, the dict field value is an Enum class instance, not the primitive value (e.g., string). It would work as intended if the enums would be encoded as typing.Literal instead.

OpenAPI:

AccessModel:
  type: object
  properties:
    access:
      type: string
      description: "Only 'readonly' or 'readwrite' is allowed"
      enum:
        - readonly
        - readwrite

Current generated model code:

class Access(Enum):
    readonly = 'readonly'
    readwrite = 'readwrite'

class AccessModel(BaseModel):
    access: Access = Field(
        ...,
        description='Only 'readonly' or 'readwrite' is allowed',
    )

Converting a model instance to a dictionary with access_model.dict() yields {'access': <Access.readonly: 'readonly'>}.

I'm proposing using typing.Literal to encode OpenAPI enums the following way:

from typing import Literal
class AccessModel(BaseModel):
    access: Literal['readonly', 'readwrite'] = Field(
        ...,
        description='Only 'readonly' or 'readwrite' is allowed',
    )

Converting an instance of this yields a dictionary with the correct primitive type: {'access': 'readonly'}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant