Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow substituting typevar-with-values for typevar-with-values #1469

Merged
merged 1 commit into from
May 3, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 8 additions & 1 deletion mypy/applytype.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from typing import List, Dict

import mypy.subtypes
from mypy.sametypes import is_same_type
from mypy.expandtype import expand_type
from mypy.types import Type, CallableType, AnyType, Void
from mypy.types import Type, TypeVarType, CallableType, AnyType, Void
from mypy.messages import MessageBuilder
from mypy.nodes import Context

Expand All @@ -29,6 +30,12 @@ def apply_generic_arguments(callable: CallableType, types: List[Type],
if values and type:
if isinstance(type, AnyType):
continue
if isinstance(type, TypeVarType) and type.values:
# Allow substituting T1 for T if every allowed value of T1
# is also a legal value of T.
if all(any(is_same_type(v, v1) for v in values)
for v1 in type.values):
continue
for value in values:
if mypy.subtypes.is_subtype(type, value):
types[i] = value
Expand Down
14 changes: 14 additions & 0 deletions mypy/test/data/check-typevar-values.test
Original file line number Diff line number Diff line change
Expand Up @@ -465,3 +465,17 @@ def g(x: str) -> str: return x
main: note: In function "f":
main:7: error: Incompatible types in assignment (expression has type "object", variable has type "int")
main:7: error: Incompatible types in assignment (expression has type "object", variable has type "str")

[case testGenericFunctionSubtypingWithTypevarValues]
from typing import TypeVar
class A: pass
T = TypeVar('T', int, str)
U = TypeVar('U', str, A, int)
def f(x: T) -> T: pass
def g(x: U) -> U: pass
a = f
a = f
a = g
b = g
b = g
b = f # E: Incompatible types in assignment (expression has type Callable[[T], T], variable has type Callable[[U], U])