python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.31k stars 2.81k forks source link

Interference between two different type variables #4425

Open JukkaL opened 6 years ago

JukkaL commented 6 years ago

Mypy rejects this fragment, apparently because the type variables AnyStr and X interfere with each other:

from typing import TypeVar, Any, Callable, AnyStr

F = TypeVar('F', bound=Callable)

def on_exception_return(to_return):
    # type: (Any) -> Callable[[F], F]
    pass

@on_exception_return(False)
def is_on(feature_name):
    # type: (AnyStr) -> bool
    return True

class A: pass
class B: pass

X = TypeVar('X', A, B)

def f(x: X) -> None:
    is_on('')

Here's the output I get:

t.py:20: error: Argument 1 to "is_on" has incompatible type "str"; expected "A"
t.py:20: error: Argument 1 to "is_on" has incompatible type "str"; expected "B"

The expected behavior is clean output.

We've already fixed a bunch of similar issues.

ilevkivskyi commented 6 years ago

IIUC having the decorator is important to trigger this. So this seems to be closely related to https://github.com/python/mypy/issues/1317, in particular to the example in https://github.com/python/mypy/issues/1317#issuecomment-341959279.