Skip to content

Counter.__init__ can't be typed safely #1846

Open
@beauxq

Description

@beauxq

Counter overloads are unsafe

from collections import Counter

# no type errors reported and nothing tricky going on
a = {"a": "hello"}
b = Counter(a)
c = b.get("a", 0)
print(c + 2)  # crash

and I think there isn't a way to express them safely in the current type system.
Iterable[_T] needs to be something like Iterable[_T] - Mapping[_T, ~int]

If type checkers want to address this now, it would probably have to be a special case.

Without having to worry about type intersections/differences/negations, maybe we could have a way to indicate:
"If this overload matches (after all previous overloads fail), a type error should be reported."

something like:

    @overload
    def __init__(self, mapping: Mapping[_T, Any], /) -> typing.Error: ...

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: otherOther topics not covered

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions