From 22275fd7f44089abbc049259771b915dd98e46c7 Mon Sep 17 00:00:00 2001 From: Matt Bush Date: Thu, 6 Nov 2025 16:47:23 -0800 Subject: [PATCH] Add support for x-enum-varnames to string enums --- ...ort_for_x_enum_varnames_to_string_enums.md | 9 ++++++ .../test_enums_and_consts.py | 29 +++++++++++++++++++ .../parser/properties/enum_property.py | 4 ++- 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 .changeset/add_support_for_x_enum_varnames_to_string_enums.md diff --git a/.changeset/add_support_for_x_enum_varnames_to_string_enums.md b/.changeset/add_support_for_x_enum_varnames_to_string_enums.md new file mode 100644 index 000000000..4b84e6da8 --- /dev/null +++ b/.changeset/add_support_for_x_enum_varnames_to_string_enums.md @@ -0,0 +1,9 @@ +--- +default: minor +--- + +# Add support for x-enum-varnames to string enums + +#1358 by @mbbush + +You can now customize the variable names of the generated string enumerations using the x-enum-varnames openapi extension. Previously, this was only possible for integer enumerations. diff --git a/end_to_end_tests/functional_tests/generated_code_execution/test_enums_and_consts.py b/end_to_end_tests/functional_tests/generated_code_execution/test_enums_and_consts.py index 4bd0b2c81..986f11036 100644 --- a/end_to_end_tests/functional_tests/generated_code_execution/test_enums_and_consts.py +++ b/end_to_end_tests/functional_tests/generated_code_execution/test_enums_and_consts.py @@ -71,6 +71,35 @@ def test_invalid_values(self, MyModel): MyModel.from_dict({"enumProp": 2}) +@with_generated_client_fixture( + """ + components: + schemas: + MyStrEnum: + type: string + enum: ["a", "b", "c"] + x-enum-varnames: [ + "One", + "More than OnE", + "not_quite_four" + ] + """) +@with_generated_code_imports( + ".models.MyStrEnum", +) +class TestStrEnumVarNameExtensions: + @pytest.mark.parametrize( + "expected_name,expected_value", + [ + ("ONE", "a"), + ("MORE_THAN_ON_E", "b"), + ("NOT_QUITE_FOUR", "c"), + ], + ) + def test_enum_values(self, MyStrEnum, expected_name, expected_value): + assert getattr(MyStrEnum, expected_name) == MyStrEnum(expected_value) + + @with_generated_client_fixture( """ components: diff --git a/openapi_python_client/parser/properties/enum_property.py b/openapi_python_client/parser/properties/enum_property.py index 725aaceba..9845da7f4 100644 --- a/openapi_python_client/parser/properties/enum_property.py +++ b/openapi_python_client/parser/properties/enum_property.py @@ -201,7 +201,9 @@ def values_from_list( else: output[f"VALUE_{value}"] = value continue - if value and value[0].isalpha(): + if use_var_names: + key = var_names[i] + elif value and value[0].isalpha(): key = value.upper() else: key = f"VALUE_{i}"