Skip to content

resulting ItemsView isn't narrowed after isinstance(..., Mapping) check (and other oddities) #11377

@posita

Description

@posita

Summary

Code sample in pyright playground

def count_the_things(
    *sources: Mapping[T, SupportsInt] | Iterable[tuple[T, SupportsInt]],
    use_keys_instead_of_items_for_maps: bool = False,
) -> Counter[T]:
    c: Counter[T] = Counter()
    for source in sources:
        if isinstance(source, Mapping):
            if use_keys_instead_of_items_for_maps:
                for outcome in source:
                    count = source[outcome]
                    reveal_type(outcome)  # should be T, but is T@count_the_things | tuple[T@count_the_things, SupportsInt]
                    reveal_type(count)  # should be SupportsInt, but is SupportsInt | Unknown
                    c[outcome] += int(count)
            else:
                for outcome, count in source.items():
                    reveal_type(outcome)  # should be T, but is T@count_the_things | tuple[T@count_the_things, SupportsInt]
                    reveal_type(count)  # should be SupportsInt, but is SupportsInt | Unknown
                    c[outcome] += int(count)
        else:
            for outcome, count in source:
                reveal_type(outcome)
                reveal_type(count)
                c[outcome] += int(count)
    return c

To be fair, pyrefly and ty both choke on this, so I probably screwed something up, but I'm pretty sure these should be narrower than they are. mypy passes (possibly related due to fixing python/mypy#11685).

Related

Version

pyright 1.1.408

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions