fix: Support types.UnionType in schemas

Since Python 3.10, unions can be expressed as `type1 | type2`. Sadly,
while this is functionally equivalent to `Union[type1, type2]`, the type
of the expression is different (`types.UnionType`, not `typing.Union`).

We should handle both in schemas.

Signed-off-by: Ihar Hrachyshka <ihar.hrachyshka@gmail.com>
This commit is contained in:
Ihar Hrachyshka 2025-03-20 10:40:26 -04:00
parent af8b4484a3
commit cd38b2594e

View file

@ -17,6 +17,7 @@ import enum
import functools import functools
import inspect import inspect
import json import json
import types
import typing import typing
import uuid import uuid
from copy import deepcopy from copy import deepcopy
@ -455,7 +456,7 @@ class JsonSchemaGenerator:
"maxItems": len(args), "maxItems": len(args),
"prefixItems": [self.type_to_schema(member_type) for member_type in args], "prefixItems": [self.type_to_schema(member_type) for member_type in args],
} }
elif origin_type is Union: elif origin_type in (Union, types.UnionType):
discriminator = None discriminator = None
if typing.get_origin(data_type) is Annotated: if typing.get_origin(data_type) is Annotated:
discriminator = typing.get_args(data_type)[1].discriminator discriminator = typing.get_args(data_type)[1].discriminator