Datamodel-code-generator: codegen for enum with operators produces attempts to reuse '_' resulting in python error

Created on 10 Mar 2021  路  4Comments  路  Source: koxudaxi/datamodel-code-generator

Describe the bug
Hi, we encountered an issue when trying to generate code for an enum that contains operators. The code that is generated reuses the _ character for field names:

class Operator(Enum):
    _ = '='
    __ = '!='
    _ = '>'
    _ = '<'
    __ = '>='
    __ = '<='

Which results in the following error when running the python program:

TypeError: Attempted to reuse key: '_'

To Reproduce

Example schema:

swagger: '2.0'
...
  operator:
    type: string
    description: Operator to filter data by.
    enum:
      - '='
      - '!='
      - '>'
      - '<'
      - '>='
      - '<='
    example: '>='
    xml:
      attribute: true

Used commandline:

$ datamodel-codegen --input foo.yaml --output model.py

Expected behavior
I would expect something like the following code to be generated (which is also more readable due to the field names):

class Operator(Enum):
    EQ = '='
    NE = '!='
    GT = '>'
    LT = '<'
    GE = '>='
    LE = '<='

Version:

  • OS: Ubuntu 18.04
  • Python version: 3.7.5
  • datamodel-code-generator version: 0.7.0
bug released

Most helpful comment

Awesome news, thank you for the really quick fix, I will check it out :)

All 4 comments

Thank you for creating this issue.

I expect x-enum-varnames to work for your case.
https://openapi-generator.tech/docs/templating/#enum

But, the option only works for numbers now :(
I will fix this feature.

openapi: 3.0
components:
  schemas:
    operator:
      type: string
      description: Operator to filter data by.
      enum:
        - '='
        - '!='
        - '>'
        - '<'
        - '>='
        - '<='
      x-enum-varnames:
        - EQ
        - NE
        - GT
        - LT 
        - GE
        - LE
      example: '>='
      xml:
        attribute: true

Thank you, much appreciated!

@pdeligia
I have released a fixed version as 0.9.2 馃帀

Output

...
from __future__ import annotations

from enum import Enum


class Operator(Enum):
    EQ = '='
    NE = '!='
    GT = '>'
    LT = '<'
    GE = '>='
    LE = '<='

Btw, you wrote swagger: '2.0'. Unfortunately, The code-gen doesn't support swagger. You should use OpenAPI 3.0

Awesome news, thank you for the really quick fix, I will check it out :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

languitar picture languitar  路  3Comments

bcbernardo picture bcbernardo  路  4Comments

Echronix picture Echronix  路  3Comments

languitar picture languitar  路  3Comments

ioggstream picture ioggstream  路  6Comments