Skip to content

Cannot customize Counter type #4032

Closed
Closed
@davidblewett

Description

@davidblewett

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.

import typing
from collections import Counter
from decimal import Decimal


def test(foo:str) -> typing.Counter[str, Decimal]:
    bar: typing.Counter[str, Decimal] = Counter({'foo': Decimal('5.0')})
    bar[foo] += Decimal('5.0')
    return bar

returns:

counter_test.py:6: error: "Counter" expects 1 type argument, but 2 given
counter_test.py:7: error: "Counter" expects 1 type argument, but 2 given
counter_test.py:7: error: Dict entry 0 has incompatible type "str": "Decimal"
counter_test.py:9: error: Incompatible types in assignment (expression has type "Decimal", target has type "int")

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions