Skip to content

feat: Type-safe "optional-nullable" fields #3779 #3791

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 27 commits into from
May 6, 2025

Conversation

nrbnlulu
Copy link
Member

@nrbnlulu nrbnlulu commented Feb 23, 2025

Description

Note that I renamed not_unset to exists bc I think its easier to read albeit more common in commit
8526fca
this is easily revertable...

Types of Changes

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

Issues Fixed or Closed by This PR

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

Adds strawberry.Maybe and strawberry.isnt_unset to handle optional and nullable input fields in mutations, providing a more type-safe and intuitive way to determine if a value is present or absent. It also includes tests and documentation for the new feature.

New Features:

  • Introduces strawberry.Maybe and strawberry.isnt_unset to handle optional and nullable input fields in mutations, providing a more type-safe and intuitive way to determine if a value is present or absent.

Enhancements:

  • Replaces the use of strawberry.UNSET with strawberry.Maybe and strawberry.isnt_unset for optional input fields, improving code readability and reducing potential errors.

Documentation:

  • Updates the release notes to include a description of the new strawberry.Maybe feature and how to use it.

Tests:

  • Adds tests to verify the behavior of strawberry.Maybe with different scenarios, including setting values from None to Some, Some to None, and handling absent values.

Copy link
Contributor

sourcery-ai bot commented Feb 23, 2025

Reviewer's Guide by Sourcery

This pull request introduces strawberry.Maybe and strawberry.isnt_unset to handle optional and nullable fields in mutations, offering a more type-safe and intuitive approach compared to using strawberry.UNSET directly. It includes a test case demonstrating the usage of the new feature and a release note describing the changes.

Updated class diagram for optional-nullable fields

classDiagram
    class Maybe~T~
    class UnsetType
    class Union~T, UnsetType, None~
    class TypeGuard~Union[T, None]~

    UnsetType <|-- Maybe~T~
    Union~T, UnsetType, None~ ..> Maybe~T~ : includes
    TypeGuard~Union[T, None]~ ..> Union~T, UnsetType, None~ : checks type of

    note for Maybe~T~ "Represents a value that can be either of type T, Unset, or None"
    note for UnsetType "Represents an unset value"
    note for Union~T, UnsetType, None~ "Type alias for T | UnsetType | None"
    note for TypeGuard~Union[T, None]~ "Type guard to check if a value is not Unset"
Loading

File-Level Changes

Change Details Files
Introduces strawberry.Maybe and strawberry.isnt_unset for handling optional and nullable fields in mutations, providing a more type-safe and intuitive approach compared to using strawberry.UNSET directly.
  • Adds Maybe type alias to represent a union of a type, UnsetType, and None.
  • Adds isnt_unset type guard to check if a value is not an instance of UnsetType.
  • Exports Maybe and isnt_unset in strawberry.__init__.py.
strawberry/types/unset.py
strawberry/__init__.py
Adds a test case demonstrating the usage of strawberry.Maybe and strawberry.isnt_unset in a mutation with an optional and nullable field.
  • Defines a User type with an optional phone field.
  • Defines an UpdateUserInput input type using strawberry.Maybe for the phone field.
  • Creates a mutation update_user that uses strawberry.isnt_unset to check if the phone field was provided in the input.
  • Adds tests to verify that the mutation correctly handles cases where the phone field is set to a value, set to None, or absent from the input.
tests/schema/test_mutation.py
Adds a release note describing the new feature.
  • Explains the motivation for the new feature.
  • Provides a code example demonstrating the usage of strawberry.Maybe and strawberry.isnt_unset.
RELEASE.md

Possibly linked issues


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!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

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 @nrbnlulu - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a changelog entry to describe the new strawberry.Maybe and strawberry.isnt_unset features.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟡 Testing: 2 issues found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

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.

RELEASE.md Outdated

Now you can use `strawberry.Maybe` and `strawberry.isnt_unset` to identify if a value was provided or not.

i.e
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (typo): Use "e.g." instead of "i.e."

"i.e." means "that is", while "e.g." means "for example". Since you're providing an example, "e.g." is more appropriate.

Suggested change
i.e
e.g.

@botberry
Copy link
Member

botberry commented Feb 23, 2025

Thanks for adding the RELEASE.md file!

Here's a preview of the changelog:


This release adds a new (preferable) way to handle optional updates. Up until
now when you wanted to inffer if an input value was null or absent you'd use
strawberry.UNSET which is a bit cumbersome and error prone.

Now you can use strawberry.Maybe to identify if a
value was provided or not.

e.g.

import strawberry


@strawberry.type
class User:
    name: str
    phone: str | None


@strawberry.input
class UpdateUserInput:
    name: str
    phone: strawberry.Maybe[str]


@strawberry.type
class Mutation:
    def update_user(self, input: UpdateUserInput) -> None:
        reveal_type(input.phone)  # strawberry.Some[str | None] | None

        if input.phone:
            reveal_type(input.phone.value)  # str | None

            update_user_phone(input.phone.value)

Or, if you can use pattern matching:

@strawberry.type
class Mutation:
    def update_user(self, input: UpdateUserInput) -> None:
        match input.phone:
            case strawberry.Some(value=value):
                update_user_phone(input.phone.value)

You can also use strawberry.Maybe as a field argument like so

import strawberry


@strawberry.field
def filter_users(self, phone: strawberry.Maybe[str] = None) -> list[User]:
    if phone:
        return filter_users_by_phone(phone.value)

    return get_all_users()

Here's the tweet text:

🆕 Release (next) is out! Thanks to ניר, @patrick and @_bellini666 for the PR 👏

This release introduces a new, more convenient way to handle optional values in Strawberry: `strawberry.Maybe`! 🎉

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

@botberry
Copy link
Member

Thanks for adding the RELEASE.md file!

Here's a preview of the changelog:


This release adds a new (preferable) way to handle optional updates.
Up until now when you wanted to inffer if an input value was null or absent you'd use strawberry.UNSET which is a bit cumbersome and error prone.

Now you can use strawberry.Maybe and strawberry.isnt_unset to identify if a value was provided or not.

i.e

import strawberry


@strawberry.type
class User:
    name: str
    phone: str | None


@strawberry.input
class UpdateUserInput:
    name: str
    phone: strawberry.Maybe[str]


@strawberry.type
class Mutation:
    def update_user(self, info, input: UpdateUserInput) -> User:
        if strawberry.isnt_unset(input.phone):
            phone = (
                input.phone
            )  # could be `str | None` in case we want to nullify the phone

        return User(name=input.name, phone=phone)

Here's the tweet text:

🆕 Release (next) is out! Thanks to ניר for the PR 👏

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

Copy link

codecov bot commented Feb 23, 2025

Codecov Report

Attention: Patch coverage is 94.90446% with 8 lines in your changes missing coverage. Please review.

Project coverage is 95.04%. Comparing base (c618232) to head (c1cbff5).
Report is 23 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3791      +/-   ##
==========================================
- Coverage   95.24%   95.04%   -0.21%     
==========================================
  Files         499      505       +6     
  Lines       32417    32856     +439     
  Branches     1681     1706      +25     
==========================================
+ Hits        30877    31227     +350     
- Misses       1275     1355      +80     
- Partials      265      274       +9     
🚀 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.

Copy link

codspeed-hq bot commented Feb 23, 2025

CodSpeed Performance Report

Merging #3791 will not alter performance

Comparing nrbnlulu:optional-nullable (c1cbff5) with main (f6ac9bb)

Summary

✅ 21 untouched benchmarks

@nrbnlulu
Copy link
Member Author

bump

@botberry
Copy link
Member

Pre-release

👋

Releasing commit [9411124] to PyPi as pre-release! 📦

@botberry
Copy link
Member

Pre-release

👋

Pre-release 0.262.7.dev.1743345593 [9411124] has been released on PyPi! 🚀
You can try it by doing:

poetry add strawberry-graphql==0.262.7.dev.1743345593

@patrick91
Copy link
Member

patrick91 commented Mar 30, 2025

@nrbnlulu I was playing with this a bit, and I don't think I like the approach, not sure if it is
different from what we have discussed in the past.

I think we should have a Maybe type that can be used directly, instead of having to use strawberry.exists,
for example:

import strawberry


@strawberry.type
class User:
    name: str
    phone: str | None


@strawberry.input
class UpdateUserInput:
    name: str
    phone: strawberry.Maybe[str | None]


@strawberry.type
class Mutation:
    def update_user(self, info, input: UpdateUserInput) -> User:
        reveal_type(input.phone)  # strawberry.Maybe[str]

        if input.phone:
            reveal_type(input.phone)  # str | None
            ...

        match input.phone:
            case strawberry.Some(phone):
                reveal_type(phone)  # str | None
                ...
            case None:
                # nothing to do
                ...

        return User(name=input.name, phone=input.phone)

what do you think? /cc @bellini666

@nrbnlulu
Copy link
Member Author

nrbnlulu commented Mar 31, 2025

@nrbnlulu I was playing with this a bit, and I don't think I like the approach, not sure if it is different from what we have discussed in the past.

I think we should have a Maybe type that can be used directly, instead of having to use strawberry.exists, for example:

import strawberry


@strawberry.type
class User:
    name: str
    phone: str | None


@strawberry.input
class UpdateUserInput:
    name: str
    phone: strawberry.Maybe[str | None]


@strawberry.type
class Mutation:
    def update_user(self, info, input: UpdateUserInput) -> User:
        reveal_type(input.phone)  # strawberry.Maybe[str]

        if input.phone:
            reveal_type(input.phone)  # str | None
            ...

        match input.phone:
            case strawberry.Some(phone):
                reveal_type(phone)  # str | None
                ...
            case None:
                # nothing to do
                ...

        return User(name=input.name, phone=input.phone)

what do you think? /cc @bellini666

yeah I took a different approach inspired by #3779 (comment) . I found it less involved..
anyways IDRC taking the type Maybe[T] = Some[T | None] | None approach.
which would it be?

@patrick91
Copy link
Member

I'd say let's go with type Maybe[T] = Some[T | None] | None :)

@nrbnlulu
Copy link
Member Author

nrbnlulu commented Apr 4, 2025

@patrick91 | @bellini666 Done

@patrick91
Copy link
Member

Just putting this down here, since we now need to also think about DX for LLMs :'D

CleanShot 2025-04-29 at 17 29 39@2x



@pytest.fixture
def maybe_schema() -> strawberry.Schema:
Copy link
Member

Choose a reason for hiding this comment

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

reminder for self, let's move this to test_maybe :)

Copy link
Member

@patrick91 patrick91 left a comment

Choose a reason for hiding this comment

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

This looks great! We'll do another pass soon for the internal, but me and @bellini666 are very excited for this to land!

Copy link
Member

@patrick91 patrick91 left a comment

Choose a reason for hiding this comment

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

who-knows-yes-gif-by-bounce

@patrick91
Copy link
Member

Sorry it took a while! This looks great! Thanks @nrbnlulu!

@patrick91 patrick91 dismissed bellini666’s stale review May 6, 2025 16:04

All good now

@patrick91 patrick91 merged commit 0185b3a into strawberry-graphql:main May 6, 2025
100 of 101 checks passed
@nrbnlulu
Copy link
Member Author

nrbnlulu commented May 6, 2025

sorry for not resolving things in time 😞

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Type-safe "optional-nullable" fields
4 participants