Skip to content

mypy stops reporting errors when reveal_type is called #6748

Open
@bwo

Description

@bwo

Consider the following code; the relevant part is in map() but the rest is included for completeness:

from typing import Generic, TypeVar, Callable

R = TypeVar('R')
L = TypeVar('L')
T = TypeVar('T')
E = TypeVar('E')


class Either(Generic[L, R]):

    def map(self, f):
        # type: (Callable[[R], T]) -> Either[L, T]
        # reveal_type(self.bimap)               # a
        # return self.bimap(lambda x: x, f)     # b
        y = self.bimap(lambda x: x, f)          # c (includes following line)
        return y

    def bimap(self, f, g):
        # type: (Callable[[L], E], Callable[[R], T]) -> Either[E, T]
        if isinstance(self, Left):
            return self.left(f(self.val))
        elif isinstance(self, Right):
            return self.right(g(self.val))
        assert False

    @classmethod
    def left(cls, lft):
        # type: (L) -> Either[L, R]
        return Left(lft)

    @classmethod
    def right(cls, rght):
        # type: (R) -> Either[L, R]
        return Right(rght)


class Left(Either[L, R]):
    def __init__(self, left):
        # type: (L) -> None
        self.val = left


class Right(Either[L, R]):
    def __init__(self, right):
        # type: (R) -> None
        self.val = right

As given, (a) and (b) are commented out and (c) is not. If I run mypy (0.701) over it, it complains:

foo.py:15: error: Cannot infer type argument 1 of "bimap" of "Either"
foo.py:15: error: Cannot infer type argument 2 of "bimap" of "Either"

If (c) is commented out and (b) is uncommented, mypy complains like so:

foo.py:14: error: Argument 2 to "bimap" of "Either" has incompatible type "Callable[[R], T]"; expected "Callable[[T], T]"

This is already strange: I would have expected return EXPR and NAME = EXPR; return NAME to be the same.

But! If I uncomment (a), then the only output is

foo.py:13: error: Revealed type is 'def [E, T] (f: def (L`1) -> E`1, g: def (R`2) -> T`2) -> foo.Either[E`1, T`2]'

I.e., it no longer finds a type error. This is true regardless of whether (b) or (c) is uncommented!

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions