Adding variable annotation causes incompatible type when Optional and TypeVars are used

Open
#4,554 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
42/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
compilers

Research direction

Start by running the minimal Python reproducer with mypy and --strict-optional, then trace how the checker infers TypeVars through Optional arguments and variable annotations. The fix is complete when the annotated bar: List[str] example type-checks without the incompatible-type error while the existing examples remain valid.

Written by the indexing model from the issue text.

Description

bug false-positive priority-1-normal

Found while playing around with attrs (now in the typeshed) and using --strict-optional:

$ mypy --version
mypy 0.570-dev-f3491a320ffa36e6574c4370489d9f4819d7fa83 (master)

$ python --version
Python 3.6.3
# Run with --strict-optional
from typing import TypeVar, Callable, Optional, List
_T = TypeVar('_T')
def make(typ: Callable[[], _T]) -> _T:
    ...
def accept(arg: Optional[_T]) -> _T:
    ...
accept(make(list))
accept(None)
foo = accept(make(list))                   # This works
bar: List[str] = accept(make(list))    # Argument 1 to "accept" has incompatible type "List[_T]"; expected "Optional[List[str]]"

Note: The real code has more arguments and an overload that handles the None case but I cut it down to the shortest repro.

The attrs version of this code is:

import attr
x: List[str] = attr.ib(attr.Factory(list))
Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.