datamodel-code-generator
datamodel-code-generator copied to clipboard
[graphql] Add support for --use-subclass-enum
Is your feature request related to a problem? Please describe.
If I define an enum in my GraphQL schema, the generator creates the Enum subclass.
enum Status {
FIRST,
SECOND,
}
class Status(Enum):
FIRST = 'FIRST'
SECOND = 'SECOND'
That suggests that, in my Python code, the values should be converter to enums (via Status(value)) before they can be used as a field value of another type. That's fine when the field is non-nullable, but it starts to be awkward if the field is nullable. It basically means to recreate some of the validation checks that would be done automatically by pydantic.
type Object {
id: String!
status: Status
}
obj = Object(
id=item["Id"],
status=Status(item["Status"]) if item["Status"] else None
)
if o.status == Status.FIRST:
...
Describe the solution you'd like
It would be great to be able to generate enums as subclasses of string via the --use-subclass-enum option. Then we could rely on pydantic to make sure that the values are valid and we could still use the enum class in the code and tests.
class Status(str, Enum):
FIRST = 'FIRST'
SECOND = 'SECOND'
o = Object(
id=item["Id"],
status=item["Status"]
)
if o.status == Status.FIRST:
...
Describe alternatives you've considered I tried to implement some helper functions as a workaround, but the suggested solution would produce a nicer code.