Skip to content

Commit

Permalink
Support multiple type enum (#309)
Browse files Browse the repository at this point in the history
  • Loading branch information
koxudaxi authored Jan 18, 2021
1 parent dffdc4f commit aa7ca9a
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 6 deletions.
13 changes: 8 additions & 5 deletions datamodel_code_generator/parser/jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def validate_exclusive_maximum_and_exclusive_minimum(
oneOf: List['JsonSchemaObject'] = []
anyOf: List['JsonSchemaObject'] = []
allOf: List['JsonSchemaObject'] = []
enum: List[str] = []
enum: List[Any] = []
writeOnly: Optional[bool]
properties: Optional[Dict[str, 'JsonSchemaObject']]
required: List[str] = []
Expand Down Expand Up @@ -697,17 +697,20 @@ def parse_enum(
enum_fields: List[DataModelFieldBase] = []

for i, enum_part in enumerate(obj.enum):
if obj.type == 'string' or (
isinstance(obj.type, list) and 'string' in obj.type
):
if obj.type == 'string' or isinstance(enum_part, str):
default = f"'{enum_part}'"
field_name = enum_part
else:
default = enum_part
if obj.x_enum_varnames:
field_name = obj.x_enum_varnames[i]
else:
field_name = f'{obj.type}_{enum_part}'
prefix = (
obj.type
if isinstance(obj.type, str)
else type(enum_part).__name__
)
field_name = f'{prefix}_{enum_part}'
enum_fields.append(
self.data_model_field_type(
name=self.model_resolver.get_valid_name(field_name),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,11 @@ class AliasEnum(Enum):
a = 1
b = 2
c = 3


class MultipleTypeEnum(Enum):
red = 'red'
amber = 'amber'
green = 'green'
NoneType_None = None
int_42 = 42
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,11 @@ class AliasEnum(Enum):
a = 1
b = 2
c = 3


class MultipleTypeEnum(Enum):
red = 'red'
amber = 'amber'
green = 'green'
NoneType_None = None
int_42 = 42
4 changes: 3 additions & 1 deletion tests/data/openapi/enum_models.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,6 @@ components:
AliasEnum:
enum: [1,2,3]
type: number
x-enum-varnames: ['a', 'b', 'c']
x-enum-varnames: ['a', 'b', 'c']
MultipleTypeEnum:
enum: [ "red", "amber", "green", null, 42 ]

0 comments on commit aa7ca9a

Please sign in to comment.