Skip to content

Missed type narrowing in assert len(r) == … which should imply r is not None #11365

@jmarshall

Description

@jmarshall

In the following code, after the first assert it would seem that the type of r could be narrowed to list[int], which would prevent the pyright diagnostic on the second assert:

def foo() -> list[int] | None:
    return [28, 37]

def bar():
    r = foo()
    reveal_type(r)  # list[int] | None
    assert len(r) == 2
    reveal_type(r)  # list[int] | None   but could be   list[int]
    assert 28 in r  # error: Operator "in" not supported for types … and "list[int] | None"

Describe the solution you’d like

Use of len(r) within the assert implies that afterwards r cannot be None, so its type can be narrowed to list[int]. With that information, the types for the in operator are appropriate and so there is no type error.

(This could be worked around with assert r and len(r) == 2 but it would be good if the existing code were diagnostic-free too.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions