Skip to content

Incorrect union narrowing in chained conditionals #12208

Closed
@JaviFuentes94

Description

@JaviFuentes94

Bug Report
Hey there!

I have recently encountered this case:

class Animal:
    name: Literal["animal"]
    n_legs: int

class Plant:
    name: Literal["plant"]

def get_n_legs(item: Union[Animal, Plant]):
    if item.name == "animal" and item.n_legs > 6:    # This fails mypy with union-attr for n_legs in Plant
        return "Many" 

Expected Behavior

Mypy should be able to narrow down chained conditionals as presented. It seems that pylance has no problems with it, for example.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions