Skip to content

Type error when creating a tuple from a Generator #5312

@jatoben

Description

@jatoben

Describe the bug

Creating a tuple[tuple[float, float]] from a Generator[tuple[float, float], None, None] fails to type-check, unless a temporary variable is used.

To Reproduce

I have an existing API which is typed like this:

class Point:
    x: float
    y: float
    # additional members here


def get_points() -> Iterable[Point]:
    ...


def convert_point(point: Point) -> tuple[float, float]:
    ...


# Can draw either a single point represented as a tuple[float, float] or a sequence of points
def draw_path(
    points: tuple[float, float] | Sequence[tuple[float, float]], *, width: float
) -> None:
    ...

If I use tuple() to turn a generator of converted points into an immutable sequence, I get the following error:

draw_path(
    tuple(convert_point(p) for p in get_points()),
    width=0.25,
)

# error: Argument of type "Generator[tuple[float, float], None, None]" cannot be assigned to parameter "__iterable" of type "Iterable[_T_co@tuple]" in function "__new__"
#    "Generator[tuple[float, float], None, None]" is incompatible with "Iterable[float]"
#      TypeVar "_T_co@Iterable" is covariant
#        "tuple[float, float]" is incompatible with "float" (reportGeneralTypeIssues)

However, capturing the created tuple in a temporary variable first prevents the error.

points = tuple(convert_point(p) for p in get_points())
draw_path(
    points,
    width=0.25,
)

Expected behavior

I would expect equivalent type-checking results from draw_path() calls.

VS Code extension or command-line

Command-line version 1.1.314

Additional context

#5281 could perhaps be related.

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