Currently, we need to set the default value to strawberry.arguments.UNSET
to support optional arguments. This object has the Any
annotation which hides itself from type checkers.
Example:
id: Optional[strawberry.ID] = UNSET
MyPy will consider id
to be a Union[ID, None]
while in reality, it's a Union[ID, None, _Unset]
. This results in potential bugs in code where the type-checker would catch it.
For example, the following snippet will raise an error without a type checker catching it:
def foo(id: Optional[str] = UNSET) -> None:
if id is not None:
print(id.lower()) # Will attempt to call `lower()` on `UNSET`
My proposal is to introduce a new type alias as a first-class citizen in the Strawberry type system:
T = TypeVar("T")
UnsetOrOptional = Union[_Unset, Optional[T]]
And its usage in resolvers:
@strawberry.field
def foo(id: UnsetOrOptional[strawberry.ID]) -> None:
pass
UNSET
to its value if it was not included in the requestThis allows us to also provide the option for resolvers to define a simpler default behavior when we only care about strawberry.ID
vs None
:
@strawberry.field
def foo(id: Optional[strawberry.ID]) -> None:
pass
None
to its value if it was not included in the requestPay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too