The strawberry.type
and strawberry.input
decorators create dataclasses, and they work fine with stdlib dataclasses
helpers like fields
and asdict
, e.g. strawberry.fields(SomeInputType)
, but mypy flags such usages as errors.
All-in-one reproducer script:
cd $(mktemp -d)
python -m venv venv
. venv/bin/activate
pip install graphql-core==3.2.3 mypy==1.2.0 mypy-extensions==1.0.0 python-dateutil==2.8.2 six==1.16.0 strawberry-graphql==0.176.3 tomli==2.0.1 typing_extensions==4.5.0
cat > file.py <<EOF
import dataclasses
import strawberry
@strawberry.type
class GqlType:
x: int
y: int
print(f"{dataclasses.is_dataclass(GqlType)=} {len(dataclasses.fields(GqlType))=} {dataclasses.asdict(GqlType(x=1, y=2))=}")
@strawberry.input
class GqlInput:
z: int
print(f"{dataclasses.is_dataclass(GqlInput)=} {len(dataclasses.fields(GqlInput))=} {dataclasses.asdict(GqlInput(z=3))=}")
EOF
cat > mypy.ini <<EOF
[mypy]
plugins = strawberry.ext.mypy_plugin
EOF
# runs fine:
python file.py
#> dataclasses.is_dataclass(GqlType)=True len(dataclasses.fields(GqlType))=2 dataclasses.asdict(GqlType(x=1, y=2))={'x': 1, 'y': 2}
#> dataclasses.is_dataclass(GqlInput)=True len(dataclasses.fields(GqlInput))=1 dataclasses.asdict(GqlInput(z=3))={'z': 3}
# BUG: mypy fails:
mypy file.py
#> file.py:9: error: No overload variant of "asdict" matches argument type "GqlType" [call-overload]
#> file.py:9: error: Argument 1 to "fields" has incompatible type "Type[GqlType]"; expected "Union[DataclassInstance, Type[DataclassInstance]]" [arg-type]
#> file.py:15: error: No overload variant of "asdict" matches argument type "GqlInput" [call-overload]
#> file.py:15: error: Argument 1 to "fields" has incompatible type "Type[GqlInput]"; expected "Union[DataclassInstance, Type[DataclassInstance]]" [arg-type]
This may relate to #2614
Thanks for strawberry π
Pay 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