graphql-python / graphene-pydantic

Integrate GraphQL with your Pydantic models
Other
224 stars 45 forks source link

Handle list[str] as a field, etc. #105

Open dmontagu opened 3 months ago

dmontagu commented 3 months ago

Ran into a bug trying to use list[int] as a field type on a BaseModel in Python 3.9. (Note it is also broken with Python 3.10.). Interestingly, things are handled correctly in these versions of python when using typing.List[str], etc., but not when using a bare list[str] (even though that is allowed in these python versions).

This pull request fixes the handling of list[str] as a field type.

The issue is that, in Python 3.9 (and 3.10), inspect.isclass(list[str]) returns True, but Python still raises an error when you try to call issubclass(list[str], BaseModel). If you explicitly check for being an instance of types.GenericAlias though, that resolves this issue, as even in these versions of python isinstance(list[str], types.GenericAlias) is True.


I'll note though that you have the comment:

    # NOTE: this has to come before any `issubclass()` checks, because annotated
    # generic types aren't valid arguments to `issubclass`

right below the change I made. I suspect this is below the pydantic model check so that you handle things properly if the pydantic model has that field (maybe? maybe not..), but if it works it might alternatively make sense to just move that branch above this if statement which is passing the type_ to issubclass. But I figured there was a higher chance that that could cause other issues, so I didn't bother.