Skip to content

Conversation

@paulo-raca
Copy link
Contributor

@paulo-raca paulo-raca commented Dec 12, 2025

Currently, Strawberry exposes the enum name in GraphQL.

This PR adds the option to use the enum values instead.

Why

I'm wrapping an existing OpenAPI service in GraphQL. There are tons of enums generated by the OpenAPI client that I want to reuse instead of writing again (also, they change often). They generated enums look like this:

class MyEnumType(str, Enum):
    FOO = 'foo'
    BAR = 'bar'
    ETC = 'etc'

Since the lowercase values are used in a ton of different places, including documentation and case-sensitive queries (e.g., findEntities('myenum eq "foo"'), I want them to stay the same everywhere.

This PR adds @strawberry.enum(use_enum_values=True), so that the GraphQL mapping uses the enum values instead of names

Types of Changes

  • Core
  • Bugfix
  • New feature
  • Enhancement/optimization
  • Documentation

Checklist

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • I have tested the changes and verified that they work and don't break anything (as well as I can manage).

Summary by Sourcery

Add support for mapping GraphQL enum values from either the Python enum names or their underlying values, controlled via a new use_enum_values option.

New Features:

  • Introduce a use_enum_values option on the @strawberry.enum decorator to emit GraphQL enums using their underlying Python values instead of names.

Enhancements:

  • Preserve compatibility with existing enums while allowing custom GraphQL names and value-based mappings.
  • Clarify enum mapping behavior in the documentation with guidance on using use_enum_values.

Tests:

  • Expand enum tests to cover both default name-based behavior and the new value-based enum mapping.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Dec 12, 2025

Reviewer's Guide

Adds support for using Python enum values instead of enum member names as GraphQL enum value names via a new use_enum_values option on @strawberry.enum, updates enum processing logic to honor this, adds tests validating both default and use_enum_values behavior, and documents the new option.

File-Level Changes

Change Details Files
Allow enums to use their Python values as GraphQL enum value names via a new use_enum_values flag on @strawberry.enum.
  • Extended _process_enum to accept a use_enum_values boolean flag and compute a graphql_name per enum member, defaulting to the enum value when use_enum_values is True and no explicit GraphQL name is set.
  • Preserved existing strawberry.enum_value behavior while routing its graphql_name into the new graphql_name variable, and only falling back to names or values when it is unset.
  • Updated EnumValue construction to use the resolved graphql_name while keeping the underlying stored value unchanged.
strawberry/types/enum.py
Expose the new use_enum_values option in the public strawberry.enum decorator API and its overloads.
  • Added use_enum_values parameter to all enum overload signatures to keep typing consistent.
  • Wired the decorator wrapper to pass use_enum_values through to _process_enum.
  • Clarified the docstring to explain the default name-based behavior and the new value-based option.
strawberry/types/enum.py
Expand tests to cover both default enum behavior (using names) and the new use_enum_values behavior (using values).
  • Adjusted an existing test to verify that default enums still use GraphQL names while supporting mixed usage of plain enum members and strawberry.enum_value with custom names in arguments and return values.
  • Added a new test test_use_enum_values that decorates an enum with @strawberry.enum(use_enum_values=True) and asserts that GraphQL accepts the enum values as literals and returns the same values.
  • Used list-typed enum fields in the test schema to exercise multiple enum values in a single query.
tests/enums/test_enum.py
Document the new capability and how to enable it.
  • Updated the enums documentation note to state that Strawberry defaults to using enum member names for GraphQL enums and mention the new @strawberry.enum(use_enum_values=True) option to use enum values instead.
docs/types/enums.md

Possibly linked issues

  • #Use @strawberry.enum value instead of name: PR implements @strawberry.enum(use_enum_values=True), directly solving the issue’s request to use enum values in GraphQL.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • When use_enum_values=True, graphql_name is taken directly from item_value, which may not be a valid GraphQL Name (or even a string); consider validating and/or coercing to str and raising a clear error if the value is not a valid GraphQL enum name.
  • The new use_enum_values flag subtly changes how input enum literals are written; it might be worth clarifying in the implementation (e.g., via a short comment near _process_enum) that use_enum_values affects the GraphQL enum names, not the underlying Enum.value, to make the semantics clear for future maintainers.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- When `use_enum_values=True`, `graphql_name` is taken directly from `item_value`, which may not be a valid GraphQL `Name` (or even a string); consider validating and/or coercing to `str` and raising a clear error if the value is not a valid GraphQL enum name.
- The new `use_enum_values` flag subtly changes how input enum literals are written; it might be worth clarifying in the implementation (e.g., via a short comment near `_process_enum`) that `use_enum_values` affects the *GraphQL enum names*, not the underlying `Enum.value`, to make the semantics clear for future maintainers.

## Individual Comments

### Comment 1
<location> `tests/enums/test_enum.py:208-217` </location>
<code_context>
+    assert res.data["foo"] == ["FOO", "BAR", "Baz"]
+
+
+def test_use_enum_values() -> None:
+    @strawberry.enum(use_enum_values=True)
+    class Foo(Enum):
+        FOO = "foo"
+        BAR = strawberry.enum_value("bar")
+        BAZ = strawberry.enum_value("baz", name="Baz")

     @strawberry.type
     class Query:
         @strawberry.field
-        def foo(self, foo: Foo) -> str:
-            return foo.value
+        def foo(self, enums: List[Foo]) -> List[Foo]:
+            assert enums == [Foo.FOO, Foo.BAR, Foo.BAZ]
+            return enums

     schema = strawberry.Schema(Query)
-    res = schema.execute_sync("{ foo(foo: BAZ) }")
+    res = schema.execute_sync("{ foo(enums: [foo, bar, Baz]) }")
     assert not res.errors
     assert res.data
-    assert res.data["foo"] == "baz"
+    assert res.data["foo"] == ["foo", "bar", "Baz"]
</code_context>

<issue_to_address>
**suggestion (testing):** Add a test for the functional `strawberry.enum(MyEnum, use_enum_values=True)` usage

Could you also add a companion test for the functional style, e.g.

```python
class Foo(Enum):
    FOO = "foo"
    BAR = strawberry.enum_value("bar")
    BAZ = strawberry.enum_value("baz", name="Baz")

FooType = strawberry.enum(Foo, use_enum_values=True)

@strawberry.type
class Query:
    @strawberry.field
    def foo(self, enums: List[FooType]) -> List[FooType]:
        return enums
```

and assert that both input literals and serialized output use the enum values (with `name=` overrides still taking precedence)? That would confirm decorator and functional forms handle `use_enum_values` consistently.
</issue_to_address>

### Comment 2
<location> `docs/types/enums.md:137-139` </location>
<code_context>

 GraphQL types are not a map of name: value, like in python enums. Strawberry
-uses the name of the members of the enum to create the GraphQL type.
+default to using the name of the members of the enum to create the GraphQL type.
+You can use their values instead with `@strawberry.enum(use_enum_values=True)`

</code_context>

<issue_to_address>
**issue (typo):** Use correct verb form: "defaults" instead of "default" after "Strawberry".

The sentence currently reads as “Strawberry default to using…”. For correct subject–verb agreement, update it to: “Strawberry defaults to using the name of the members of the enum to create the GraphQL type.”

```suggestion
GraphQL types are not a map of name: value, like in python enums. Strawberry
defaults to using the name of the members of the enum to create the GraphQL type.
You can use their values instead with `@strawberry.enum(use_enum_values=True)`
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@botberry
Copy link
Member

botberry commented Dec 12, 2025

Thanks for adding the RELEASE.md file!

Here's a preview of the changelog:


Support using enum values in the GraphQL schema

Here's the tweet text:

🆕 Release (next) is out! Thanks to Paulo Costa for the PR 👏

Get it here 👉 https://strawberry.rocks/release/(next)

@botberry
Copy link
Member

Hi, thanks for contributing to Strawberry 🍓!

We noticed that this PR is missing a RELEASE.md file. We use that to automatically do releases here on GitHub and, most importantly, to PyPI!

So as soon as this PR is merged, a release will be made 🚀.

Here's an example of RELEASE.md:

Release type: patch

Description of the changes, ideally with some examples, if adding a new feature.

Release type can be one of patch, minor or major. We use semver, so make sure to pick the appropriate type. If in doubt feel free to ask :)

Here's the tweet text:

🆕 Release (next) is out! Thanks to Paulo Costa for the PR 👏

Get it here 👉 https://strawberry.rocks/release/(next)

@greptile-apps
Copy link
Contributor

greptile-apps bot commented Dec 12, 2025

Greptile Overview

Greptile Summary

This PR adds use_enum_values=True option to @strawberry.enum decorator, allowing GraphQL schemas to use Python enum values instead of names. This is particularly useful when wrapping existing OpenAPI-generated enums that use lowercase values.

Key Changes:

  • Added use_enum_values parameter to enum() decorator and _process_enum() function
  • Updated GraphQL name selection logic to respect: custom name parameter from strawberry.enum_value() > use_enum_values setting > default enum name
  • Added comprehensive test coverage for the new feature
  • Updated documentation to explain the new option

Implementation Quality:

  • The logic correctly handles the precedence of naming strategies
  • Custom names from strawberry.enum_value(name=...) take priority over use_enum_values
  • Backward compatible - existing code without use_enum_values maintains current behavior
  • Tests verify both simple enum values and complex cases with strawberry.enum_value() customization

Confidence Score: 5/5

  • This PR is safe to merge with minimal risk
  • The implementation is straightforward, backward compatible, and well-tested. The feature adds a simple boolean flag that doesn't affect existing functionality. The logic correctly handles edge cases where custom names from strawberry.enum_value() should take precedence over the use_enum_values setting.
  • No files require special attention

Important Files Changed

File Analysis

Filename Score Overview
strawberry/types/enum.py 5/5 Added use_enum_values parameter to enum decorator and processing logic; implementation correctly handles precedence: custom name parameter > use_enum_values setting > default enum name
tests/enums/test_enum.py 5/5 Added comprehensive test for use_enum_values=True feature and renamed existing test for clarity; tests cover both standard enum values and strawberry.enum_value() with custom names
docs/types/enums.md 5/5 Updated documentation to explain the new use_enum_values option with clear guidance on default behavior

Sequence Diagram

sequenceDiagram
    participant User
    participant Decorator as @strawberry.enum
    participant ProcessEnum as _process_enum()
    participant EnumValue as EnumValue
    participant Schema as Schema Converter
    participant GraphQL as GraphQL Schema

    User->>Decorator: Define enum with use_enum_values=True
    Decorator->>ProcessEnum: Pass use_enum_values flag
    
    loop For each enum member
        ProcessEnum->>ProcessEnum: Check if value is EnumValueDefinition
        alt Has EnumValueDefinition with custom name
            ProcessEnum->>EnumValue: Use custom graphql_name from enum_value()
        else use_enum_values=True
            ProcessEnum->>EnumValue: Use enum.value as graphql_name
        else Default behavior
            ProcessEnum->>EnumValue: Use enum.name as graphql_name
        end
        ProcessEnum->>ProcessEnum: Create EnumValue with graphql_name
    end
    
    ProcessEnum->>Schema: Return StrawberryEnumDefinition
    Schema->>GraphQL: Convert to GraphQLEnumType
    GraphQL->>User: Enum values exposed in schema
Loading

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 files reviewed, no comments

Edit Code Review Agent Settings | Greptile

@codecov
Copy link

codecov bot commented Dec 12, 2025

Codecov Report

❌ Patch coverage is 95.65217% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.22%. Comparing base (3bde027) to head (fc44e22).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #4071   +/-   ##
=======================================
  Coverage   94.22%   94.22%           
=======================================
  Files         540      540           
  Lines       35426    35461   +35     
  Branches     1870     1872    +2     
=======================================
+ Hits        33379    33412   +33     
- Misses       1737     1738    +1     
- Partials      310      311    +1     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@codspeed-hq
Copy link

codspeed-hq bot commented Dec 12, 2025

CodSpeed Performance Report

Merging #4071 will not alter performance

Comparing paulo-raca:enum-names (fc44e22) with main (3bde027)

Summary

✅ 28 untouched

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants