python / python/mypy

Type Variable Specialized by Generic

Open
#6,387 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-1-normal topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

It seems that Type[...] variables dont specialize correctly:

Types = Union[int, str]
T = TypeVar('T', bound=Types)

class A:
    x: Types
    y: Type[Types]

class B(A, Generic[T]):
    x: T        # ok
    y: Type[T]  # error: Incompatible types in assignment

The error that arises is

error: Incompatible types in assignment (expression has type "Type[T]", base class "A" defined the type as "Union[Type[int], Type[str]]")

I believe this is a bug and it should be an allowed specialization (similar to the instance x above), unless there is a counterexample I'm not thinking of?

Tested with mypy v0.660 as well as mypy master + typed-ast master, CPython 3.7.1

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

Use the supplied Python snippet as the reproducer and inspect the type-checking path for generic attribute overrides involving Type[T] and Union bounds. Done means mypy accepts y: Type[T] in B without the incompatible-assignment error, with a regression check for this example.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.