-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Cannot customize Counter type #4032
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
Comments
import typing
from collections import Counter
from decimal import Decimal
DecimalCounter = typing.NewType('DecimalCounter', Counter)
def test(foo:str) -> DecimalCounter:
bar: DecimalCounter = Counter({'foo': Decimal('5.0')})
bar[foo] += Decimal('5.0')
return bar returns:
|
import typing
from collections import Counter
from decimal import Decimal
DecimalDict = typing.Dict[str, Decimal]
def test(foo:str) -> DecimalDict:
bar: DecimalDict = Counter({'foo': Decimal('5.0')})
bar[foo] += Decimal('5.0')
return bar returns:
|
I don't think this is related to mypy or typing. You are asking for a different kind of Counter implementation; this issue should be filed elsewhere (maybe discussed in python-ideas mailing list). What's wrong with simply using defaultdict? |
The behavior of Counter has been very useful with other types of values than int. The docs even say:
|
Your example does not require Counter. Adding another type argument will complicate the common use case. Besides, what should be the second type? It can't safely be some unbounded T. It will require some dedicated protocol. |
Either the stub needs to be extended to match the behavior of the actual implementation in the stdlib (I don't know, I've never used Counter myself). In that case, please file a PR with the typeshed project. Or this requires a change in the stdlib. In which case please take the discussion to bugs.python.org. |
When |
I believe the last time I looked into this, I concluded that Counter isn't actually supposed to use other value types than |
required as the issue seems to be stuck in limbo, see python/mypy#4032
I had a situation where I wanted a collections.Counter that had string keys and Decimal values, but it appears that the current typing definition of it is set to Counter[str] with int values, and no way of specifying a different type for values.
returns:
I tried various approaches using typing.NewType , but couldn't figure out a combination to create a definition that could override the existing one for typing.Counter.
The text was updated successfully, but these errors were encountered: