Skip to content

Narrowing str | dict[str, str] with isinstance and .get() #13351

@Akuli

Description

@Akuli

Bug Report

To Reproduce

def first() -> None:
    tag_name: str | dict[str, str]
    if isinstance(tag_name, dict):
        tag_name = tag_name.get("foo", "bar")
    reveal_type(tag_name)

def second() -> None:
    tag_name: str | dict[str, str]
    if isinstance(tag_name, dict):
        tag_name = tag_name["foo"]
    reveal_type(tag_name)

Expected Behavior

str
str

Actual Behavior

Union[str, dict[str, str]]
str

Your Environment

latest mypy

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inferencetopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions