graphene-pydantic icon indicating copy to clipboard operation
graphene-pydantic copied to clipboard

Handle list[str] as a field, etc.

Open dmontagu opened this issue 8 months ago • 0 comments

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.

dmontagu avatar Jun 11 '24 17:06 dmontagu