Skip to content

Type annotation for collections.Counter looks doubtful #8768

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
fischbacher opened this issue Sep 19, 2022 · 1 comment
Closed

Type annotation for collections.Counter looks doubtful #8768

fischbacher opened this issue Sep 19, 2022 · 1 comment

Comments

@fischbacher
Copy link

fischbacher commented Sep 19, 2022

Right here, we find:

class Counter(dict[_T, int], Generic[_T]):

Now, the standard library reference says:

https://docs.python.org/3.9/library/collections.html#collections.Counter

-->
A Counter is a dict subclass for counting hashable objects. ...
...
Note Counters were primarily designed to work with positive integers to represent running counts; however, care was taken to not unnecessarily preclude use cases needing other types or negative values. To help with those use cases, this section documents the minimum range and type restrictions.
The Counter class itself is a dictionary subclass with no restrictions on its keys and values. The values are intended to be numbers representing counts, but you could store anything in the value field.
-->

So, overall, there are two relevant aspects here:

  1. collections.Counter instances are dict instances, hence bound by the dict contract.
  2. It is explicitly considered valid to have non-int values. (Due to 1., it would not be valid to forbid that - but it is also explicitly stated as permitted.)

This means that it is not valid to make a statement such as: "A collections.Counter[str] is a dict[str, int]". Rather, collections.Counter needs to be doubly-parametric (like dict) with respect to both key- and value-type:

A statement such as "A collections.Counter[str, numbers.Integral] is a dict[str, numbers.Integral]" would be typing-wise somewhat defensible. As long as we are not talking about mutability, it would be actually defensible. If we consider mutability, there is a separate issue, a revival of what has become known as "the ML reference problem" - but irrespective of that, collections.Counter cannot validly be singly-parametric with respect to key-type only.

@srittau
Copy link
Collaborator

srittau commented Sep 19, 2022

Duplicate of #3438. This change would most likely break a lot of type annotations as long as we don't have type var defaults.

@srittau srittau closed this as not planned Won't fix, can't repro, duplicate, stale Sep 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants