python / python/mypy

Inconsistent handling of unsolved TypeVars

Open
#10,241 1 comment 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

PEP 484 doesn't provide much clarity about the situation where a TypeVar is provided with no value in a generic function call, so I'm not sure if there is a "correct" behavior. However, I'd expect that the behavior would at least be consistent for a type checker.

from typing import Optional, TypeVar

T1 = TypeVar("T1")
def func1(suffix: Optional[T1] = ...) -> T1:
    ...

T2 = TypeVar("T2", bound=str)
def func2(suffix: Optional[T2] = ...) -> T2:
    ...

T3 = TypeVar("T3", str, bytes)
def func3(suffix: Optional[T3] = ...) -> T3:
    ...

T4 = TypeVar("T4", bytes, str)
def func4(suffix: Optional[T4] = ...) -> T4:
    ...

reveal_type(func1()) # <nothing>
reveal_type(func2()) # <nothing>
reveal_type(func3()) # str
reveal_type(func4()) # bytes

Note that mypy's results depend on whether the TypeVar is bound or constrained. If it is constrained, mypy appears to (arbitrarily?) choose the first constrained type.

Note that this situation arises in some common situations like the following:

from tempfile import mkstemp
_, temp_path = mkstemp()
reveal_type(temp_path) # str?

Like I said, I'm not sure what the "correct" or intended behavior is in this case, but the current behavior strikes me as inconsistent.

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.

Research direction

No files or tests are named. Start by reproducing the four generic function examples and the mkstemp() case, then compare the inferred types for unconstrained, bound, and constrained TypeVars. Done requires an agreed and consistent behavior, followed by implementation and regression coverage.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.