Skip to content

isinstance check does not narrow inferred type correctly on nested Union type #3196

Closed
@betaveros

Description

@betaveros
from typing import Union

class A: pass
class B: pass
class C: pass

def foo(bar: Union[Union[A, B], C]) -> None:
    if isinstance(bar, A):
        reveal_type(bar)
    else:
        reveal_type(bar)

The last line reveals Union[A, B, C] when it should be just Union[B, C]. It works if the type of bar is replaced by Union[A, B, C].

(Of course you'd probably never directly write Union[Union[A, B], C], but it's reasonable to write Union[AB, C] where AB is an alias for Union[A, B]. And the typing module documentation says Unions of Unions are flattened.)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions