Skip to content

tagged-union narrowing via enum-literal attributes in match/case #2897

@jack-volantautonomy

Description

@jack-volantautonomy

Summary

We are currently suffering from a lot of false errors being raised with our type aliasing with scenarios like the following:

from typing import Literal, TypeAlias

from pydantic import BaseModel


class _FruitBase(BaseModel):
    id: UUID
    taste: str

class Orange(_FruitBase):
    type: Literal[FruitType.Citrus] = FruitType.Citrus

class Strawberry(_FruitBase):
    type: Literal[FruitType.Berry] = FruitType.Berry
    strawberry_exclusive_params: StrawberryExclusiveParams

CafeFruit: TypeAlias = Orange | Strawberry

def example_method(fruits: list[CafeFruit]):
    for fruit in fruits:
        match fruit.type:
            case FruitType.Berry:  # Should be able to infer fruit: Strawberry
                 foo = fruit.strawberry_exclusive_params  # <--- Issue flags here

Which would raise "error[unresolved-attribute]: Attribute strawberry_exclusive_params is not defined on Orange in union Orange | Strawberry"

Apologies if this issue has already been raised but we're getting a lot of these being flagged by ty but not by any of our other linters that we run in parallel like pyright and the pylance language server works perfectly with this scenario.

Version

ty 0.0.18

Metadata

Metadata

Assignees

Labels

narrowingrelated to flow-sensitive type narrowing

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions