Skip to content

Commit

Permalink
Make detection of TypeVar defaults robust to the CPython PEP-696 impl…
Browse files Browse the repository at this point in the history
…ementation
  • Loading branch information
AlexWaygood committed May 11, 2024
1 parent 7061f36 commit 862ebe7
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions pydantic/_internal/_generate_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -1660,15 +1660,20 @@ def _unsubstituted_typevar_schema(self, typevar: typing.TypeVar) -> core_schema.

bound = typevar.__bound__
constraints = typevar.__constraints__
default = getattr(typevar, '__default__', None)

if (bound is not None) + (len(constraints) != 0) + (default is not None) > 1:
try:
typevar_has_default = typevar.has_default() # type: ignore
except AttributeError:
# could still have a default if it's an old version of typing_extensions.TypeVar
typevar_has_default = getattr(typevar, '__default__', None) is not None

if (bound is not None) + (len(constraints) != 0) + typevar_has_default > 1:
raise NotImplementedError(
'Pydantic does not support mixing more than one of TypeVar bounds, constraints and defaults'
)

if default is not None:
return self.generate_schema(default)
if typevar_has_default:
return self.generate_schema(typevar.__default__) # type: ignore
elif constraints:
return self._union_schema(typing.Union[constraints]) # type: ignore
elif bound:
Expand Down

0 comments on commit 862ebe7

Please sign in to comment.