Skip to content
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

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

nrbnlulu
Copy link
Member

@nrbnlulu nrbnlulu commented Feb 23, 2025

Description

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.

Comment on lines +279 to +280
@strawberry.input
class UpdateUserInput:
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Suggest adding a test case for default values with Maybe.

It would be beneficial to add a test case that specifically checks the behavior of strawberry.Maybe when a default value is provided in the input type. This will ensure that the default value is correctly handled when the field is not provided in the mutation input.

Comment on lines +281 to +282
phone: strawberry.Maybe[str] = (
strawberry.UNSET
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Test case for explicitly providing UNSET.

While the current tests cover setting the value to None and omitting the field, it would be helpful to have a test case where strawberry.UNSET is explicitly passed as the input value. This would ensure that the intended behavior of UNSET is maintained and differentiated from None.

Suggested implementation:

import pytest

@pytest.mark.asyncio
async def test_explicit_unset():
    input_data = UpdateUserInput(phone=UNSET)
    # Simulate update logic or simply check that phone remains UNSET
    # In a full mutation, UNSET should signal that the field is not updated.
    assert input_data.phone is UNSET

If your update mutation uses UpdateUserInput to modify a user's data, please integrate this test with the mutation execution and assert that the user's phone remains unchanged when phone is UNSET.

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.

RELEASE.md Outdated
Comment on lines +29 to +31
phone = (
input.phone
) # could be `str | None` in case we want to nullify the phone
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Handle the case where input.phone is unset

The example code doesn't define phone outside the if block. It should initialize phone with the existing value or None before the if block.

@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)

@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

All modified and coverable lines are covered by tests ✅

Project coverage is 97.24%. Comparing base (951e56c) to head (6974df2).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #3791   +/-   ##
=======================================
  Coverage   97.23%   97.24%           
=======================================
  Files         503      503           
  Lines       33529    33593   +64     
  Branches     1716     1717    +1     
=======================================
+ Hits        32603    32667   +64     
  Misses        707      707           
  Partials      219      219           

Copy link

codspeed-hq bot commented Feb 23, 2025

CodSpeed Performance Report

Merging #3791 will not alter performance

Comparing nrbnlulu:optional-nullable (6974df2) with main (951e56c)

Summary

✅ 21 untouched benchmarks

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.

Type-safe "optional-nullable" fields
2 participants