diff --git a/CHANGELOG.md b/CHANGELOG.md index 26bfd500..11b6fecb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## UNRELEASED - Fixed generating results for nullable fields with nullable directives. +- Added escaping of enum values which are Python keywords by appending `_` to them. ## 0.9.0 (2023-09-11) diff --git a/ariadne_codegen/client_generators/enums.py b/ariadne_codegen/client_generators/enums.py index 53d83da6..56a19e9d 100644 --- a/ariadne_codegen/client_generators/enums.py +++ b/ariadne_codegen/client_generators/enums.py @@ -1,4 +1,5 @@ import ast +from keyword import iskeyword from typing import List, Optional, cast from graphql import GraphQLEnumType, GraphQLSchema @@ -48,12 +49,14 @@ def _filter_enum_types(self) -> List[GraphQLEnumType]: ] def _parse_enum_definition(self, definition: GraphQLEnumType) -> ast.ClassDef: - fields = [ - generate_assign([val_name], generate_constant(val_def.value), lineno) - for lineno, (val_name, val_def) in enumerate( - definition.values.items(), start=1 + fields: List[ast.stmt] = [] + for lineno, (val_name, val_def) in enumerate( + definition.values.items(), start=1 + ): + name = val_name if not iskeyword(val_name) else val_name + "_" + fields.append( + generate_assign([name], generate_constant(val_def.value), lineno) ) - ] class_def = generate_class_def( name=definition.name, diff --git a/tests/client_generators/test_enums_generator.py b/tests/client_generators/test_enums_generator.py index 61e035d2..bdcbf83b 100644 --- a/tests/client_generators/test_enums_generator.py +++ b/tests/client_generators/test_enums_generator.py @@ -31,6 +31,8 @@ def test_generate_returns_module_with_enum_class_definition(): enum CustomEnum { VALUE1 VALUE2 + from + import } """ expected_class_def = ast.ClassDef( @@ -45,6 +47,12 @@ def test_generate_returns_module_with_enum_class_definition(): ast.Assign( targets=[ast.Name(id="VALUE2")], value=ast.Constant(value="VALUE2") ), + ast.Assign( + targets=[ast.Name(id="from_")], value=ast.Constant(value="from") + ), + ast.Assign( + targets=[ast.Name(id="import_")], value=ast.Constant(value="import") + ), ], ) generator = EnumsGenerator(schema=build_ast_schema(parse(schema_str)))