8000 Properly support type variable defaults by Viicos · Pull Request #11332 · pydantic/pydantic · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Feedback
  • Loading branch information
Viicos committed Jan 24, 2025
commit ec82c4782afeddbc633f1b4177cd27b6a973bad7
4 changes: 2 additions & 2 deletions pydantic/_internal/_generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,8 +386,8 @@ def has_instance_in_type(type_: Any, isinstance_target: Any) -> bool:
def map_generic_model_arguments(cls: type[BaseModel], args: tuple[Any, ...]) -> dict[TypeVar, Any]:
"""Return a mapping between the arguments of a generic model and the provided arguments during parametrization.

If the number of arguments does not match the parameters (e.g. if providing too few or too many arguments),
a `TypeError` is raised.
Raises:
TypeError: If the number of arguments does not match the parameters (i.e. if providing too few or too many arguments).

Example:
```python {test="skip" lint="skip"}
Expand Down
4 changes: 3 additions & 1 deletion pydantic/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -767,8 +767,10 @@ def __class_getitem__(
if not isinstance(typevar_values, tuple):
typevar_values = (typevar_values,)

# For a model `class Model[T, U, V = int](BaseModel): ...` parametrized with `(str, bool)`,
# this gives us `{T: str, U: bool, V: int}`:
typevars_map = _generics.map_generic_model_arguments(cls, typevar_values)
# In case type variables have defaults and a type wasn't provided, use the defaults:
# We also update the provided args to use defaults values (`(str, bool)` becomes `(str, bool, int)`):
typevar_values = tuple(v for v in typevars_map.values())

if _utils.all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map:
Expand Down
8 changes: 4 additions & 4 deletions tests/test_generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,13 +308,13 @@ class Model(BaseModel, Generic[T, S]):

def test_arguments_count_validation() -> None:
T = TypeVar('T')
S = TypeVar('S')
U = TypingExtensionsTypeVar('U', default=int)
U = TypeVar('U')
V = TypingExtensionsTypeVar('V', default=int)

class Model(BaseModel, Generic[T, S, U]):
class Model(BaseModel, Generic[T, U, V]):
t: T
s: S
u: U
v: V

model_repr = repr(Model)

Expand Down
Loading
0