question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

codegen for enum with empty string

See original GitHub issue

Is your feature request related to a problem? Please describe.

Environment

datamodel-code-generator==0.9.3

Scenario

Wanted to generate pydantic models from docker engine API.

datamodel-codegen --url "https://converter.swagger.io/api/convert?url=https://docs.docker.com/engine/api/v1.30.yaml"

Note that docker engine api uses openapi 2.0 spec. Therefore, I used converter.swagger.io to translate it into 3.0.0.

Error message

Traceback (most recent call last):
  File "<my_path>/python3.7/site-packages/datamodel_code_generator/__main__.py", line 424, in main
    strict_types=config.strict_types,
  File "<my_path>/python3.7/site-packages/datamodel_code_generator/__init__.py", line 311, in generate
    results = parser.parse()
  File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/base.py", line 386, in parse
    self.parse_raw()
  File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/openapi.py", line 34, in parse_raw
    [*path_parts, '#/components', 'schemas', obj_name],
  File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/jsonschema.py", line 997, in parse_raw_obj
    self.parse_obj(name, JsonSchemaObject.parse_obj(raw), path)
  File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/jsonschema.py", line 1002, in parse_obj
    self.parse_object(name, obj, path)
  File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/jsonschema.py", line 624, in parse_object
    fields=self.parse_object_fields(obj, path),
  File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/jsonschema.py", line 571, in parse_object_fields
    field_type = self.parse_enum(field_name, field, [*path, field_name])
  File "<my_path>/python3.7/site-packages/datamodel_code_generator/parser/jsonschema.py", line 820, in parse_enum
    name=self.model_resolver.get_valid_name(field_name),
  File "<my_path>/python3.7/site-packages/datamodel_code_generator/reference.py", line 362, in get_valid_name
    if name[0] == '#':
IndexError: string index out of range

Cause

The docker engine openapi spec defines a schema with an Enum that contains an empty string:

    RestartPolicy:
      type: object
      properties:
        Name:
          type: string
          description: ...
          enum:
          - ""   # here
          - always
          - unless-stopped
          - on-failure

It seems that get_valid_name cannot handle empty strings.

Describe the solution you’d like

I’ve tested the following workaround by changing the function get_valid_name as below.

def get_valid_name(self, name: str, camel: bool = False) -> str:
    if not name:    # +
        return "_"     # +
    if name.isidentifier():
        return name
    if name[0] == '#':
        name = name[1:]   # note that original error is caused here. 
    ...

The resulting enum is

class Name(Enum):
    """
        - Empty string means not to restart
    - `always` Always restart
    - `unless-stopped` Restart always except when the user has manually stopped the container
    - `on-failure` Restart only when the container exit code is non-zero

    """

    _ = ''
    always = 'always'
    unless_stopped = 'unless-stopped'
    on_failure = 'on-failure'

Describe alternatives you’ve considered

If we are targeting python 3.8 and above, this issue can be easily mitigated by using --enum-field-as-literal all. Therefore this issue can be resolved by allowing --enum-field-as-literal option in python 3.7 by importing Literal from typing_extensions.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:11 (11 by maintainers)

github_iconTop GitHub Comments

2reactions
yuyupopocommented, Mar 21, 2021

Thank you too!

1reaction
koxudaxicommented, Mar 21, 2021

@yuyupopo I have released a new version as 0.9.4 Thank you very much!!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Should Enums be allowed to have empty string values? #627
I'd like to suggest that enum shapes should not be modeled with enum values of empty string. With validation returning and error if...
Read more >
Setting Empty String for Enum Value in Java - Stack Overflow
Save this question. Show activity on this post. I have an object in Java which I am trying to set from an enum...
Read more >
Openapi enum null values - SmartBear Community
I want to have enums that can have null values. ... 'The Type of the Item' type: string nullable: true enum: - "PHYSICAL"...
Read more >
Enums - Swagger
Nullable enums. A nullable enum can be defined as follows: type: string; nullable: true # <---; enum: - asc; - desc; - null...
Read more >
typescript-resolvers - GraphQL Code Generator
Codegen allows you to specify either mappers or enumValues to map enums in your resolvers, and if you are using it for enums,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found