Skip to content

Type checking for higher order function with variadic generics fails without variable assignment #5113

@sylee957

Description

@sylee957

Describe the bug

Given the functions:

from __future__ import annotations

from collections.abc import Callable
from typing import TypeVar, TypeVarTuple

X = TypeVar("X")
Y = TypeVar("Y")
Xs = TypeVarTuple("Xs")
Ys = TypeVarTuple("Ys")


def nil() -> tuple[()]:
    return ()


def cons(
    f: Callable[[X], Y],
    g: Callable[[*Xs], tuple[*Ys]],
) -> Callable[[X, *Xs], tuple[Y, *Ys]]:
    def wrapped(x: X, *xs: *Xs) -> tuple[Y, *Ys]:
        y, ys = f(x), g(*xs)
        return y, *ys

    return wrapped


def star(f: Callable[[X], Y]) -> Callable[[*tuple[X, ...]], tuple[Y, ...]]:
    def wrapped(*xs: X):
        if not xs:
            return nil()
        return cons(f, star(f))(*xs)

    return wrapped

I get an error

test.py:31:29 - error: Argument of type "(X@star) -> Y@star" cannot be assigned to parameter "f" of type "(X@star) -> Y@star" in function "star"
    Type "(X@star) -> Y@star" cannot be assigned to type "(X@star) -> Union[*Ys@cons]"
      Function return type "Y@star" is incompatible with type "Union[*Ys@cons]"
        Type "Y@star" cannot be assigned to type "Union[*Ys@cons]" (reportGeneralTypeIssues)
1 error, 0 warnings, 0 informations

However, if I use the walrus trick to store the temporary variable, the issue is not present.

def star(f: Callable[[X], Y]) -> Callable[[*tuple[X, ...]], tuple[Y, ...]]:
    def wrapped(*xs: X):
        if not xs:
            return nil()
        return cons(f, _ := star(f))(*xs)

    return wrapped

The issue is also not present in pyright 1.1.305, and appears after update.

VS Code extension or command-line

I'm using pyright 1.1.308

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    addressed in next versionIssue is fixed and will appear in next published versionbugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions