Skip to content

Conversation

patrick91
Copy link
Member

@patrick91 patrick91 commented Jul 29, 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

Refactor the Maybe type definition to avoid redundant nesting of None and update the GraphQL schema converter to handle the new StrawberryMaybe type accordingly

Enhancements:

  • Simplify the Maybe type alias to Union[Some[T], None] by removing the nested None
  • Extend schema_converter.from_maybe_optional to recognize and unwrap StrawberryMaybe instances

Summary by Sourcery

Refine strawberry.Maybe to represent Some[T] | None by default, disallow explicit nulls for Maybe[T], and require Maybe[T | None] for nullability. Update conversion logic, schema generation, and validation rules accordingly, provide a codemod for migration, and enrich documentation and tests.

New Features:

  • Introduce MaybeNullValidationRule to enforce that Maybe[T] fields cannot receive explicit null values
  • Add ConvertMaybeToOptional codemod and register it in the upgrade CLI for migrating Maybe[T] to Maybe[T | None]

Enhancements:

  • Simplify Maybe type alias to Union[Some[T], None] and update argument conversion to handle StrawberryMaybe correctly
  • Update schema_converter.from_maybe_optional to unwrap nested Optionals and generate the proper GraphQL types for Maybe
  • Expand tests to cover nuanced Maybe[T] vs Maybe[T | None] behavior across inputs, resolvers, nested types, and schema generation

Documentation:

  • Add dedicated Maybe documentation in docs/types/maybe.md and link to it from resolvers and input-types guides
  • Document breaking changes for v0.279.0 about the new Maybe semantics

Tests:

  • Add comprehensive tests for MaybeNullValidationRule, resolver and input field validation, type checking, and codemod behavior

Chores:

  • Register MaybeNullValidationRule in schema validation rules and add the maybe-optional codemod to the CLI

Copy link
Contributor

sourcery-ai bot commented Jul 29, 2025

Reviewer's Guide

This PR refactors Strawberry’s Maybe type so that Maybe[T] now represents “Some[T] or None” (no longer allowing explicit null inside Some), and explicit null support is now achieved via Maybe[T | None]. It updates core type definitions, argument and schema conversion logic, adds validation rules to reject nulls for Maybe[T], provides a codemod to migrate code, updates CLI commands, revises documentation, and adjusts tests accordingly.

File-Level Changes

Change Details Files
Redefine Maybe alias to Union[Some[T], None]
  • Change type alias in types/maybe.py
  • Update typing code in TYPE_CHECKING branch
strawberry/types/maybe.py
Adjust argument conversion to unwrap and wrap Maybe correctly
  • Handle StrawberryMaybe before StrawberryOptional in convert_argument
  • Distinguish Maybe[T] vs Maybe[T
None] when unwrapping
Update schema conversion to treat Maybe as always optional
  • Extend from_maybe_optional to detect StrawberryMaybe
  • Unwrap nested StrawberryOptional inside StrawberryMaybe
strawberry/schema/schema_converter.py
Add validation rule to reject explicit nulls for Maybe[T]
  • Implement MaybeNullValidationRule in validation_rules
  • Register the rule in schema validation pipeline
strawberry/schema/schema.py
strawberry/schema/validation_rules/maybe_null.py
Introduce codemod for migrating Maybe[T] to Maybe[T None]
  • Add ConvertMaybeToOptional command
  • Map new codemod in CLI upgrade commands
Revise documentation to reflect new Maybe behavior
  • Add maybe.md with comprehensive usage
  • Update input-types.md and resolvers.md to reference maybe.md
  • Add breaking-changes entry for v0.279.0
docs/types/maybe.md
docs/types/input-types.md
docs/types/resolvers.md
docs/breaking-changes/0.279.0.md
Adjust and expand tests for new semantics
  • Update existing schema tests to use Maybe[Union[T,None]]
  • Add tests for rejecting nulls on Maybe[T]
  • Update typechecker messages
  • Add validation rule tests
tests/schema
tests/typecheckers/test_maybe.py
tests/codemods/test_maybe_optional.py
tests/schema/validation_rules

Assessment against linked issues

Issue Objective Addressed Explanation
#3779 Implement a type-safe way to distinguish between optional, nullable, and absent fields in Strawberry input types, replacing the UNSET pattern with a minimal Option/Maybe type.
#3779 Change the definition of Maybe to be Union[Some[T], None] (i.e., Some[T] None), so that Maybe[str] does not accept explicit nulls, and Maybe[str None] does, providing consistent and type-safe field presence checking.
#3779 Update documentation and validation logic to reflect the new Maybe semantics, including migration instructions, usage patterns, and codemod for automatic codebase updates.

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!

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

codecov bot commented Jul 29, 2025

Codecov Report

❌ Patch coverage is 91.93324% with 58 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.26%. Comparing base (e151370) to head (b9c0180).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3961      +/-   ##
==========================================
- Coverage   94.41%   94.26%   -0.15%     
==========================================
  Files         528      533       +5     
  Lines       34371    34863     +492     
  Branches     1803     1854      +51     
==========================================
+ Hits        32450    32864     +414     
- Misses       1630     1693      +63     
- Partials      291      306      +15     
🚀 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 Jul 29, 2025

CodSpeed Performance Report

Merging #3961 will not alter performance

Comparing fix/maybe-none (b9c0180) with main (f48434d)

Summary

✅ 26 untouched benchmarks

@patrick91 patrick91 marked this pull request as ready for review August 19, 2025 16:06
@botberry
Copy link
Member

botberry commented Aug 19, 2025

Thanks for adding the RELEASE.md file!

Here's a preview of the changelog:


This release changes the strawberry.Maybe type to provide a more consistent and intuitive API for handling optional fields in GraphQL inputs.

Breaking Change: The Maybe type definition has been changed from Union[Some[Union[T, None]], None] to Union[Some[T], None]. This means:

  • Maybe[str] now only accepts string values or absent fields (refuses explicit null)
  • Maybe[str | None] accepts strings, null, or absent fields (maintains previous behavior)

This provides a cleaner API where if field is not None consistently means "field was provided" for all Maybe fields. A codemod is available to automatically migrate your code: strawberry upgrade maybe-optional

See the breaking changes documentation for migration details.

Here's the tweet text:

🆕 Release (next) is out! Thanks to @patrick91 for the PR 👏

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

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.

Greptile Summary

This PR implements a significant refactoring of Strawberry's Maybe type system by changing the type definition from Union[Some[Union[T, None]], None] to Union[Some[T], None]. This change eliminates redundant nesting of None values and provides clearer semantics for handling optional-nullable fields in GraphQL schemas.

The core change affects how developers distinguish between "field not provided" and "field explicitly set to null" scenarios. With the new implementation:

  • Maybe[T] represents fields that can be absent or contain a value of type T, but cannot be explicitly set to null
  • Maybe[T | None] represents fields that can be absent, contain a value of type T, or be explicitly set to null

The PR includes comprehensive changes across the codebase:

  • Type System: Updated the Maybe type alias in strawberry/types/maybe.py to remove nested None handling
  • Schema Conversion: Modified schema_converter.py to properly handle the new StrawberryMaybe type structure
  • Validation: Added MaybeNullValidationRule to enforce type-safe semantics at the GraphQL validation layer
  • Argument Processing: Updated argument conversion logic to properly wrap values in Some() containers
  • Migration Support: Created a ConvertMaybeToOptional codemod to help users migrate existing code
  • Documentation: Added comprehensive documentation explaining the new Maybe semantics and migration strategies
  • Testing: Extensive test coverage for the new behavior patterns

This change addresses issue #3779 by providing a more intuitive and type-safe approach to handling optional fields. The new system ensures that if field is not None consistently means "field was provided" regardless of whether the field allows null values, making the API more predictable and reducing developer errors.

Confidence score: 2/5

  • This PR introduces complex breaking changes that could cause significant issues if the migration tooling or validation rules don't work correctly
  • Score reflects the high complexity of the type system changes and potential for runtime errors if validation rules fail
  • Pay close attention to strawberry/cli/commands/upgrade/__init__.py which has a critical bug preventing the new codemod from being used, and tests/schema/validation_rules/__init__.py which accidentally removes essential validation logic

19 files reviewed, 3 comments

Edit Code Review Bot Settings | Greptile

Comment on lines +25 to +39
def test_simple_maybe_union_syntax(self) -> None:
before = """
from strawberry import Maybe

field: Maybe[str]
"""

after = """
from strawberry import Maybe
from typing import Union

field: Maybe[Union[str, None]]
"""

self.assertCodemod(before, after, use_pipe_syntax=False)
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Duplicate test - test_simple_maybe_union_syntax has identical logic to test_simple_maybe. Consider removing or differentiating them.

Context Used: Context - In tests involving Pydantic models, ensure that the tests accurately reflect the intended behavior by using the correct instances and values. Avoid copy-pasting code that may lead to confusion. (link)

Comment on lines +92 to +97
# Resolve the actual GraphQL field name using the same logic as NameConverter
if field_def.graphql_name is not None:
field_name = field_def.graphql_name
else:
# Apply auto_camel_case conversion if enabled (default behavior)
field_name = to_camel_case(field_def.python_name)
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: The field name resolution logic assumes auto_camel_case is enabled by default, but should handle cases where it's disabled in schema configuration

Comment on lines +121 to +133
def _get_type_name(self, type_: Any) -> str:
"""Get a readable type name for error messages."""
if hasattr(type_, "__name__"):
return type_.__name__
# Handle Strawberry types that don't have __name__
if hasattr(type_, "of_type") and hasattr(type_.of_type, "__name__"):
# For StrawberryList, StrawberryOptional, etc.
return (
f"list[{type_.of_type.__name__}]"
if "List" in str(type_.__class__)
else type_.of_type.__name__
)
return str(type_)
Copy link
Contributor

Choose a reason for hiding this comment

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

style: The type name extraction logic could fail for complex nested types. Consider adding more robust handling for generic types and edge cases

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:

  • ConvertMaybeToOptional currently assumes any ‘Maybe’ symbol is from Strawberry—consider enhancing import resolution to avoid transforming unrelated types.
  • The new convert_argument logic rearranges StrawberryMaybe and StrawberryOptional handling; adding inline comments or extracting helper methods could clarify the intended branch order and reduce complexity.
  • Double-check the insertion point of MaybeNullValidationRule in validate_document to ensure it runs in the correct order relative to other validation rules.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- ConvertMaybeToOptional currently assumes any ‘Maybe’ symbol is from Strawberry—consider enhancing import resolution to avoid transforming unrelated types.
- The new convert_argument logic rearranges StrawberryMaybe and StrawberryOptional handling; adding inline comments or extracting helper methods could clarify the intended branch order and reduce complexity.
- Double-check the insertion point of MaybeNullValidationRule in validate_document to ensure it runs in the correct order relative to other validation rules.

## Individual Comments

### Comment 1
<location> `strawberry/codemods/maybe_optional.py:87` </location>
<code_context>
+    def _already_includes_none(self, node: BaseExpression) -> bool:
</code_context>

<issue_to_address>
The _already_includes_none method may not handle all edge cases for complex type expressions.

It currently checks for T | None and Union[..., None], but may not detect Optional[T] or nested unions. Please update the logic or clarify its limitations in the documentation.
</issue_to_address>

### Comment 2
<location> `strawberry/schema/validation_rules/maybe_null.py:121` </location>
<code_context>
+                            )
+                        )
+
+    def _get_type_name(self, type_: Any) -> str:
+        """Get a readable type name for error messages."""
+        if hasattr(type_, "__name__"):
+            return type_.__name__
+        # Handle Strawberry types that don't have __name__
+        if hasattr(type_, "of_type") and hasattr(type_.of_type, "__name__"):
+            # For StrawberryList, StrawberryOptional, etc.
+            return (
+                f"list[{type_.of_type.__name__}]"
+                if "List" in str(type_.__class__)
+                else type_.of_type.__name__
+            )
+        return str(type_)
+
+
</code_context>

<issue_to_address>
Type name resolution in _get_type_name may produce verbose or unclear names for complex types.

The use of str(type_) for complex types can make error messages harder to interpret. Please refine this logic to generate clearer type names for nested or generic types.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    def _get_type_name(self, type_: Any) -> str:
        """Get a readable type name for error messages."""
        if hasattr(type_, "__name__"):
            return type_.__name__
        # Handle Strawberry types that don't have __name__
        if hasattr(type_, "of_type") and hasattr(type_.of_type, "__name__"):
            # For StrawberryList, StrawberryOptional, etc.
            return (
                f"list[{type_.of_type.__name__}]"
                if "List" in str(type_.__class__)
                else type_.of_type.__name__
            )
        return str(type_)
=======
    def _get_type_name(self, type_: Any) -> str:
        """Get a readable type name for error messages, including nested/generic types."""
        # Handle built-in types and custom classes
        if hasattr(type_, "__name__"):
            return type_.__name__

        # Handle StrawberryList, StrawberryOptional, StrawberryUnion, etc.
        type_class_name = type_.__class__.__name__
        if hasattr(type_, "of_type"):
            inner_name = self._get_type_name(type_.of_type)
            if "List" in type_class_name:
                return f"list[{inner_name}]"
            if "Optional" in type_class_name or "Maybe" in type_class_name:
                return f"Optional[{inner_name}]"
            return inner_name

        # Handle StrawberryUnion
        if hasattr(type_, "types"):
            union_names = [self._get_type_name(t) for t in type_.types]
            return f"Union[{', '.join(union_names)}]"

        # Fallback: try to get a readable name, avoid verbose str(type_)
        if hasattr(type_, "_type_definition") and hasattr(type_._type_definition, "name"):
            return type_._type_definition.name

        # Last resort: use repr to avoid verbose module path
        return repr(type_)
>>>>>>> REPLACE

</suggested_fix>

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 +121 to +133
def _get_type_name(self, type_: Any) -> str:
"""Get a readable type name for error messages."""
if hasattr(type_, "__name__"):
return type_.__name__
# Handle Strawberry types that don't have __name__
if hasattr(type_, "of_type") and hasattr(type_.of_type, "__name__"):
# For StrawberryList, StrawberryOptional, etc.
return (
f"list[{type_.of_type.__name__}]"
if "List" in str(type_.__class__)
else type_.of_type.__name__
)
return str(type_)
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion: Type name resolution in _get_type_name may produce verbose or unclear names for complex types.

The use of str(type_) for complex types can make error messages harder to interpret. Please refine this logic to generate clearer type names for nested or generic types.

Suggested change
def _get_type_name(self, type_: Any) -> str:
"""Get a readable type name for error messages."""
if hasattr(type_, "__name__"):
return type_.__name__
# Handle Strawberry types that don't have __name__
if hasattr(type_, "of_type") and hasattr(type_.of_type, "__name__"):
# For StrawberryList, StrawberryOptional, etc.
return (
f"list[{type_.of_type.__name__}]"
if "List" in str(type_.__class__)
else type_.of_type.__name__
)
return str(type_)
def _get_type_name(self, type_: Any) -> str:
"""Get a readable type name for error messages, including nested/generic types."""
# Handle built-in types and custom classes
if hasattr(type_, "__name__"):
return type_.__name__
# Handle StrawberryList, StrawberryOptional, StrawberryUnion, etc.
type_class_name = type_.__class__.__name__
if hasattr(type_, "of_type"):
inner_name = self._get_type_name(type_.of_type)
if "List" in type_class_name:
return f"list[{inner_name}]"
if "Optional" in type_class_name or "Maybe" in type_class_name:
return f"Optional[{inner_name}]"
return inner_name
# Handle StrawberryUnion
if hasattr(type_, "types"):
union_names = [self._get_type_name(t) for t in type_.types]
return f"Union[{', '.join(union_names)}]"
# Fallback: try to get a readable name, avoid verbose str(type_)
if hasattr(type_, "_type_definition") and hasattr(type_._type_definition, "name"):
return type_._type_definition.name
# Last resort: use repr to avoid verbose module path
return repr(type_)

Comment on lines +202 to +203
if input.name is not None:
return f"Updated to: {input.name.value}"
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Avoid conditionals in tests. (no-conditionals-in-tests)

ExplanationAvoid complex code, like conditionals, in test functions.

Google's software engineering guidelines says:
"Clear tests are trivially correct upon inspection"
To reach that avoid complex code in tests:

  • loops
  • conditionals

Some ways to fix this:

  • Use parametrized tests to get rid of the loop.
  • Move the complex logic into helpers.
  • Move the complex part into pytest fixtures.

Complexity is most often introduced in the form of logic. Logic is defined via the imperative parts of programming languages such as operators, loops, and conditionals. When a piece of code contains logic, you need to do a bit of mental computation to determine its result instead of just reading it off of the screen. It doesn't take much logic to make a test more difficult to reason about.

Software Engineering at Google / Don't Put Logic in Tests

Comment on lines +246 to +247
if input.name is not None:
return f"Updated to: {input.name.value}"
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Avoid conditionals in tests. (no-conditionals-in-tests)

ExplanationAvoid complex code, like conditionals, in test functions.

Google's software engineering guidelines says:
"Clear tests are trivially correct upon inspection"
To reach that avoid complex code in tests:

  • loops
  • conditionals

Some ways to fix this:

  • Use parametrized tests to get rid of the loop.
  • Move the complex logic into helpers.
  • Move the complex part into pytest fixtures.

Complexity is most often introduced in the form of logic. Logic is defined via the imperative parts of programming languages such as operators, loops, and conditionals. When a piece of code contains logic, you need to do a bit of mental computation to determine its result instead of just reading it off of the screen. It doesn't take much logic to make a test more difficult to reason about.

Software Engineering at Google / Don't Put Logic in Tests

Comment on lines +285 to +286
if input.name is not None:
return f"Updated to: {input.name.value}"
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Avoid conditionals in tests. (no-conditionals-in-tests)

ExplanationAvoid complex code, like conditionals, in test functions.

Google's software engineering guidelines says:
"Clear tests are trivially correct upon inspection"
To reach that avoid complex code in tests:

  • loops
  • conditionals

Some ways to fix this:

  • Use parametrized tests to get rid of the loop.
  • Move the complex logic into helpers.
  • Move the complex part into pytest fixtures.

Complexity is most often introduced in the form of logic. Logic is defined via the imperative parts of programming languages such as operators, loops, and conditionals. When a piece of code contains logic, you need to do a bit of mental computation to determine its result instead of just reading it off of the screen. It doesn't take much logic to make a test more difficult to reason about.

Software Engineering at Google / Don't Put Logic in Tests

Comment on lines +285 to +286
if input.name is not None:
return f"Updated to: {input.name.value}"
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): We've found these issues:

schema = strawberry.Schema(query=Query, mutation=Mutation)

# Test 1: Valid values for all fields
query1 = """
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Extract duplicate code into function (extract-duplicate-method)

schema = strawberry.Schema(query=Query, mutation=Mutation)

# Test 1: Valid lists for both fields
query1 = """
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Extract duplicate code into function (extract-duplicate-method)

schema = strawberry.Schema(query=Query)

# Test 1: Valid values for both arguments
query1 = """
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Extract duplicate code into function (extract-duplicate-method)



def test_maybe_graphql_schema_consistency():
"""Test GraphQL schema generation for Maybe types.
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): We've found these issues:

@patrick91 patrick91 merged commit edb8348 into main Aug 19, 2025
106 of 108 checks passed
@patrick91 patrick91 deleted the fix/maybe-none branch August 19, 2025 17:12
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