python / mypy

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

Unexpected error while unifying Callable with TypeVar #5605

Closed alunduil closed 1 year ago

alunduil commented 6 years ago

I'm not sure if this is a bug or user error but wanted to get it documented so if others happen to come across the same issue they can hopefully find resolution.

The larger piece of code that I'm checking is here: https://github.com/alunduil/crumbs/blob/191ab997d7d312e926c494e19e97953c76864edc/crumbs/__init__.py#L441

The error can be viewed here: https://travis-ci.org/alunduil/crumbs/jobs/426535501#L612

I believe a minimal repro would be:

A = TypeVar("A")
f: Optional[Callable[[str], A]] = None
f = lambda x: str(x)

Which errors with:

error: Incompatible types in assignment (expression has type "Callable[[str], str]", variable has type "Optional[Callable[[str], A]]")
Incompatible return value type (got "str", expected "A")

I would expect this to resolve correctly, but believe that the unification is getting specified by the assignment. In the full example I linked earlier, this is protected by a conditional which I would expect (probably wrongly) to preserve the type variable.

@JukkaL mentioned in https://github.com/python/mypy/issues/2288#issuecomment-420209506, that the type is existentially qualified but my expectation would be for a universally qualified type. Are type variables meant for existential typing? Alternatively, did I write something funny and I have an existential type when I expected a universal type?

mypy: 0.620 (I haven't tried master yet) python: 3.6.6

The repro example earlier was a dry mypy run with no options, but I have been using --strict.

Let me know if any other information would be useful.

hauntsaninja commented 1 year ago

This is incorrect use of type variable, modern mypy has better error