Skip to content

Commit

Permalink
Support use of TypeVar on generic subclasses (#842)
Browse files Browse the repository at this point in the history
* Add failing generic subclass test

* Only raise type parameter failure on base GenericModel class

* Add changes to describe PR #842

* Change the class check to use is

* Fix formatting in subclass test

* correct change
  • Loading branch information
zpencerq authored and samuelcolvin committed Sep 30, 2019
1 parent 6f97c0f commit 2539835
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
1 change: 1 addition & 0 deletions changes/842-zpencerq.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Only check ``TypeVar`` param on base ``GenericModel`` class
2 changes: 1 addition & 1 deletion pydantic/generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def __class_getitem__( # type: ignore
raise TypeError('Cannot parameterize a concrete instantiation of a generic model')
if not isinstance(params, tuple):
params = (params,)
if any(isinstance(param, TypeVar) for param in params): # type: ignore
if cls is GenericModel and any(isinstance(param, TypeVar) for param in params): # type: ignore
raise TypeError(f'Type parameters should be placed on typing.Generic, not GenericModel')
if Generic not in cls.__bases__:
raise TypeError(f'Type {cls.__name__} must inherit from typing.Generic before being parameterized')
Expand Down
10 changes: 10 additions & 0 deletions tests/test_generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,16 @@ class Result(GenericModel[T]):
assert str(exc_info.value) == f'Type parameters should be placed on typing.Generic, not GenericModel'


@skip_36
def test_subclass_can_be_genericized():
T = TypeVar('T')

class Result(GenericModel, Generic[T]):
pass

Result[T]


@skip_36
def test_parameter_count():
T = TypeVar('T')
Expand Down

0 comments on commit 2539835

Please sign in to comment.