Skip to content

TypeVars can't be assigned to other TypeVars #6541

Closed
@SKHecht

Description

@SKHecht

I've found a few cases of mypy throwing errors saying that two TypeVars are incompatible instead of simply assigning one TypeVar to another. Here's the simplest example:

from typing import TypeVar
S = TypeVar('S')
T = TypeVar('T')
def foo(x: S) -> T:
    return x

mypy says:

m.py:5: error: Incompatible return value type (got "S", expected "T")

The error doesn't seem to appear if any of the TypeVars gets assigned a concrete type. mypy has no issues with this file:

from typing import Callable, TypeVar
T = TypeVar('T')
S = TypeVar('S')
def format(x: T, formatter: Callable[[T], S]) -> S:
    return formatter(x)
format(0, lambda y: y)

However, if I make the lambda a default value:

from typing import Callable, TypeVar
T = TypeVar('T')
S = TypeVar('S')
def format(x: T, formatter: Callable[[T], S] = lambda y: y) -> S:
    return formatter(x)
format(0)

mypy gives this error

n.py:4: error: Incompatible default for argument "formatter" (default has type "Callable[[T], T]", argument has type "Callable[[T], S]")
n.py:4: error: Incompatible return value type (got "T", expected "S")

I suspect this is related to #4814

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions