Skip to content

Mypy appears to infer the correct type, but throws an error. #8517

Closed
@ninjaaron

Description

@ninjaaron

Thanks so much for Mypy! It's a very useful tool.

I was messing around to see if I could write a generic iterator type in Python that would be faster than a generator function. (needless to say, I did not succeed). However, I got a rather unusual message from mypy:

otheriter.py:28: error: Incompatible return value type (got "V", expected "V")
Found 1 error in 1 file (checked 1 source file)

So, it expected the thing it got and then showed an error anyway.

Code is here:

from typing import TypeVar, Generic, Callable, Tuple, Optional

S = TypeVar("S")
V = TypeVar("V")


class Sequence:
    __slots__ = "state", "f"

    def __init__(self, state: S):
        """

        """
        self.state = state

    def __call__(self, func: Callable[[S], Optional[Tuple[V, S]]]):
        self.f = func
        return self

    def __iter__(self):
        return type(self)(self.state)(self.f)

    def __next__(self) -> V:
        out = self.f(self.state)
        if out is None:
            raise StopIteration
        val, self.state = out
        return val


@Sequence((0, 1))
def fibs(state: Tuple[int, int]) -> Optional[Tuple[int, Tuple[int, int]]]:
    a, b = state
    if a > 1_000_000_000:
        return None
    return a, (b, a+b)

When I add generic parameters to the class, I get a different error.

defining the class this way:

class Sequence(Generic[S, V]):
    ...

produces this error:

otheriter.py:31: error: Argument 1 to "__call__" of "Sequence" has incompatible type "Callable[[Tuple[int, int]], Optional[Tuple[int, Tuple[int, int]]]]"; expected "Callable[[Tuple[int, int]], Optional[Tuple[<nothing>, Tuple[int, int]]]]"
Found 1 error in 1 file (checked 1 source file)

It says it expected <nothing> in there. I don't know what that is.

Sorry if this is a duplicate.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic-descriptorsProperties, class vs. instance attributestopic-runtime-semanticsmypy doesn't model runtime semantics correctly

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions