Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions RELEASE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Release type: patch

This release fixes the usage of `strawberry.Maybe` inside modules using `from __future__ import annotations`
10 changes: 10 additions & 0 deletions strawberry/types/maybe.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import re
import typing
from typing import TYPE_CHECKING, Any, Generic, TypeAlias, TypeVar, Union

Expand Down Expand Up @@ -36,7 +37,16 @@ def __bool__(self) -> bool:
class Maybe(Generic[T]): ...


_maybe_re = re.compile(r"^(?:strawberry\.)?Maybe\[(.+)\]$")


def _annotation_is_maybe(annotation: Any) -> bool:
if isinstance(annotation, str):
# Ideally we would try to evaluate the annotation, but the args inside
# may still not be available, as the module is still being constructed.
# Checking for the pattern should be good enough for now.
return _maybe_re.match(annotation) is not None

return (orig := typing.get_origin(annotation)) and orig is Maybe


Expand Down
68 changes: 68 additions & 0 deletions tests/schema/test_maybe_future_annotations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
from __future__ import annotations

from textwrap import dedent

import strawberry
from strawberry import Maybe


def test_maybe_annotation_from_strawberry():
global MyInput
try:

@strawberry.input
class MyInput:
my_value: strawberry.Maybe[str]

@strawberry.type
class Query:
@strawberry.field
def test(self, my_input: MyInput) -> str:
return "OK"

schema = strawberry.Schema(query=Query)
expected_schema = dedent("""
input MyInput {
myValue: String
}

type Query {
test(myInput: MyInput!): String!
}
""").strip()
assert str(schema) == expected_schema

assert MyInput()
finally:
del MyInput


def test_maybe_annotation_directly():
global MyInput
try:

@strawberry.input
class MyInput:
my_value: Maybe[str]

@strawberry.type
class Query:
@strawberry.field
def test(self, my_input: MyInput) -> str:
return "OK"

schema = strawberry.Schema(query=Query)
expected_schema = dedent("""
input MyInput {
myValue: String
}

type Query {
test(myInput: MyInput!): String!
}
""").strip()
assert str(schema) == expected_schema

assert MyInput()
finally:
del MyInput
Loading