diff --git a/mypy/constraints.py b/mypy/constraints.py index ba9136a33b22..14e6ea2e6649 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -169,7 +169,7 @@ def visit_instance(self, template: Instance) -> List[Constraint]: if (self.direction == SUBTYPE_OF and template.type.has_base(instance.type.fullname())): mapped = map_instance_to_supertype(template, instance.type) - for i in range(len(instance.args)): + for i in range(min(len(mapped.args), len(instance.args))): # The constraints for generic type parameters are # invariant. Include the default constraint and its # negation to achieve the effect. diff --git a/mypy/test/data/semanal-errors.test b/mypy/test/data/semanal-errors.test index 08e993872abc..6c2e16b2a6b5 100644 --- a/mypy/test/data/semanal-errors.test +++ b/mypy/test/data/semanal-errors.test @@ -72,6 +72,24 @@ y = 0 # type: A[A] main:5: error: "B" expects 1 type argument, but 2 given main:6: error: "A" expects no type arguments, but 1 given +[case testInvalidNumberOfGenericArgsWithExplicitArgument] +from typing import TypeVar, Generic +t = TypeVar('t') +class A(object): + def __init__(self, a: t) -> None: + self.a = a +x = A(a=1) # type: A[None] +[out] +main:6: error: "A" expects no type arguments, but 1 given + +[case testInvalidNumberOfGenericArgsInInstantiatedType] +from typing import TypeVar, Generic +t = TypeVar('t') +class A(Generic[t]): pass +x = A() # type: X[None, None] +[out] +main:4: error: "A" expects 1 type argument, but 2 given + [case testInvalidNumberOfGenericArgsInUndefinedArg] class A: pass