microsoft / pyright

Static Type Checker for Python
Other
13.41k stars 1.47k forks source link

Match statement reassigning variable results in inconsistent type inference #9418

Open alessiogaldy opened 5 days ago

alessiogaldy commented 5 days ago

Describe the bug

When a variable is reassigned by a match statement pattern match the type of the variable in the match statement block is incorrectly inferred to the type before the reassignment.

Code example

@dataclass(frozen=True)
class Ok:
    value: str

@dataclass(frozen=True)
class Error:
    error: str

Result = Ok | Error

def get_result() -> Result:
    return Error("ERROR")

result = get_result()
match result:
    case Ok(value):
        print(value)
    case Error(result): # The type of result is correctly inferred as str
        print(result.error) # The type is Result again and using .error is not flagged as an error

VS Code extension or command-line This repros both using Pylance version v2024.11.1 in VSCode and Pyright version 1.1.388 from the CLI.

erictraut commented 4 days ago

Thanks for the bug report.

This will be addressed in the next release.