strawberry icon indicating copy to clipboard operation
strawberry copied to clipboard

Consider making from_pydantic take in kwargs instead of a dict to enhance mypy type checking

Open thejaminator opened this issue 2 years ago • 0 comments

Feature Request Type

  • [ ] Core functionality
  • [x ] Alteration (enhancement/optimization) of existing feature(s)
  • [ ] New behavior

Description

Currently the function signature of from_pydantic is

@staticmethod
def from_pydantic(
    instance: PydanticModel, extra: Dict[str, Any] = None
) -> StrawberryTypeFromPydantic[PydanticModel]:
        ...

Suppose you have these models

class MyModel(BaseModel):
   name: str

@strawberry.experimental.pydantic.type(MyModel, all_fields=True)
class MyModelStrawberry:
    name: str
    location: str

To fill up the location, you'll need to do

MyModel(name="james").from_pydantic(extra={"location": "san francisco"})

Since extra is a dict, mypy can't analyse location whether it needs to be a string or not

Suppose was just **kwargs instead.

MyModel(name="james").from_pydantic(location="san francisco")

That makes it possible to analyse that location should be a string, and not an int, etc by enhancing our mypy plugin. You can also then check if the strawberry type needs an extra parameter to be passed in (e.g. fields that have no defaults).

thejaminator avatar May 04 '22 17:05 thejaminator