Skip to content

Persist type checks across later conditional blocks with the same condition #2199

Closed
@Terrance

Description

@Terrance

Describe the feature

It would be nice for later use of the same conditional check to share its type "context", so that the likes of bound variables and type narrowing can be referenced later, without needing to set otherwise-unused defaults or recheck types.

Current behaviour

def func(flag: bool, value: Optional[str]):
    if flag:
        num = 1
        assert value
        reveal_type(value)  # Type of "value" is "str"
    ...
    if flag:
        print(num)  # "num" is possibly unbound
        reveal_type(value)  # Type of "value" is "str | None"

Expected behavior

Because the same* condition is used, any type logic that applied within the previous uses of the condition should apply here too. In this case, num is always defined and value is always narrowed when flag is set.

*In my case I am looking at a single bool flag here for the condition, so I'd be happy with an exact syntax match rather than an equivalence if the latter is trickier to achieve.

VS Code extension or command-line

Pyright 1.1.162 in VSCode.

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