Skip to content

Issue with decorator and generic type arguments #7033

Closed
@saulshanabrook

Description

@saulshanabrook

I seem to be getting some odd incorrect types when I wrap a method in a decorator and that method takes generic parameters.

Here is a minimal example that should pass type checking, but fails on the last line with Incompatible return value type (got "Abstraction[V, V]", expected "Abstraction[T, V]"):

from __future__ import annotations


import typing

T = typing.TypeVar("T")
U = typing.TypeVar("U")
V = typing.TypeVar("V")


def decorator(f: T) -> T:
    ...


class Abstraction(typing.Generic[T, U]):
    @decorator
    def __add__(self, other: Abstraction[U, V]) -> Abstraction[T, V]:
        ...


def fn() -> Abstraction[T, V]:
    return Abstraction[T, U]() + Abstraction[U, V]()

And here is a slightly more realistic version of the same example, with the same error:

from __future__ import annotations


import typing

T = typing.TypeVar("T")
U = typing.TypeVar("U")
V = typing.TypeVar("V")


def decorator(f: T) -> T:
    ...


class Abstraction(typing.Generic[T, U]):
    def __init__(self, fn: typing.Callable[[T], U]):
        ...

    @decorator
    def __add__(self, other: Abstraction[U, V]) -> Abstraction[T, V]:
        ...


def fn(f1: typing.Callable[[T], U], f2: typing.Callable[[U], V]) -> Abstraction[T, V]:
    return Abstraction(f1) + Abstraction(f2)

I tested this with the last master commit:

$ mypy --version
mypy 0.720+dev.48916e63403645730a584d6898fbe925d513a841

I tried it with the new semantic analyzer on and off and I get the same result.

EDIT: Not that if I do not use the decorator both of these examples type check properly.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions