Repository: samuelcolvin/pydantic (python)

Issue:
typing.Counter is not supported
### Checks

* [x] I added a descriptive title to this issue
* [x] I have searched (google, github) for similar issues and couldn't find anything
* [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug

# Bug

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
             pydantic version: 1.7
            pydantic compiled: True
                 install path: /home/user/app/.venv/lib/python3.8/site-packages/pydantic
               python version: 3.8.6 (default, Sep 25 2020, 09:36:53)  [GCC 10.2.0]
                     platform: Linux-5.9.0-1-amd64-x86_64-with-glibc2.29
     optional deps. installed: ['typing-extensions']
```

Minimal example:

```python
from typing import Counter
from pydantic import BaseModel
class ProcessedDoc(BaseModel):
    named_entities: Counter[str]
```

Result:

```text
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pydantic/main.py", line 262, in pydantic.main.ModelMetaclass.__new__
  File "pydantic/fields.py", line 315, in pydantic.fields.ModelField.infer
  File "pydantic/fields.py", line 284, in pydantic.fields.ModelField.__init__
  File "pydantic/fields.py", line 356, in pydantic.fields.ModelField.prepare
  File "pydantic/fields.py", line 492, in pydantic.fields.ModelField._type_analysis
IndexError: tuple index out of range
```



Pull request description:
Add ability to use Counter type
<!-- Thank you for your contribution! -->
<!-- Unless your change is trivial, please create an issue to discuss the change before creating a PR -->
<!-- See https://pydantic-docs.helpmanual.io/contributing/ for help on Contributing -->

## Change Summary

Add ability to use `typing.Counter` as a model field type.

## Related issue number
closes #2060 

## Checklist

* [x] Unit tests for the changes exist
* [x] Tests pass on CI and coverage remains at 100%
* [x] Documentation reflects the changes where applicable
* [x] `changes/<pull request or issue id>-<github username>.md` file added describing change
  (see [changes/README.md](https://github.com/samuelcolvin/pydantic/blob/master/changes/README.md) for details)
* [x] My PR is ready to review, **please add a comment including the phrase "please review" to assign reviewers**


Patch:
diff --git a/changes/2060-uriyyo.md b/changes/2060-uriyyo.md
new file mode 100644
index 000000000..cede2c1d3
--- /dev/null
+++ b/changes/2060-uriyyo.md
@@ -0,0 +1,1 @@
+Add ability to use `typing.Counter` as a model field type.
\ No newline at end of file
diff --git a/pydantic/fields.py b/pydantic/fields.py
index 94a2ce799..a15d0ab58 100644
--- a/pydantic/fields.py
+++ b/pydantic/fields.py
@@ -1,8 +1,9 @@
-from collections import defaultdict, deque
+from collections import Counter as CollectionCounter, defaultdict, deque
 from collections.abc import Hashable as CollectionsHashable, Iterable as CollectionsIterable
 from typing import (
     TYPE_CHECKING,
     Any,
+    Counter,
     DefaultDict,
     Deque,
     Dict,
@@ -292,6 +293,7 @@ SHAPE_GENERIC = 10
 SHAPE_DEQUE = 11
 SHAPE_DICT = 12
 SHAPE_DEFAULTDICT = 13
+SHAPE_COUNTER = 14
 SHAPE_NAME_LOOKUP = {
     SHAPE_LIST: 'List[{}]',
     SHAPE_SET: 'Set[{}]',
@@ -302,9 +304,10 @@ SHAPE_NAME_LOOKUP = {
     SHAPE_DEQUE: 'Deque[{}]',
     SHAPE_DICT: 'Dict[{}]',
     SHAPE_DEFAULTDICT: 'DefaultDict[{}]',
+    SHAPE_COUNTER: 'Counter[{}]',
 }
 
-MAPPING_LIKE_SHAPES: Set[int] = {SHAPE_DEFAULTDICT, SHAPE_DICT, SHAPE_MAPPING}
+MAPPING_LIKE_SHAPES: Set[int] = {SHAPE_DEFAULTDICT, SHAPE_DICT, SHAPE_MAPPING, SHAPE_COUNTER}
 
 
 class ModelField(Representation):
@@ -630,6 +633,10 @@ class ModelField(Representation):
             self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
             self.type_ = get_args(self.type_)[1]
             self.shape = SHAPE_DEFAULTDICT
+        elif issubclass(origin, Counter):
+            self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
+            self.type_ = int
+            self.shape = SHAPE_COUNTER
         elif issubclass(origin, Dict):
             self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
             self.type_ = get_args(self.type_)[1]
@@ -900,6 +907,8 @@ class ModelField(Representation):
             return result, None
         elif self.shape == SHAPE_DEFAULTDICT:
             return defaultdict(self.type_, result), None
+        elif self.shape == SHAPE_COUNTER:
+            return CollectionCounter(result), None
         else:
             return self._get_mapping_value(v, result), None
 


Test patch:
diff --git a/tests/test_main.py b/tests/test_main.py
index 27ecdfdee..4a968104a 100644
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -2,7 +2,7 @@ import sys
 from collections import defaultdict
 from copy import deepcopy
 from enum import Enum
-from typing import Any, Callable, ClassVar, DefaultDict, Dict, List, Mapping, Optional, Type, get_type_hints
+from typing import Any, Callable, ClassVar, Counter, DefaultDict, Dict, List, Mapping, Optional, Type, get_type_hints
 from uuid import UUID, uuid4
 
 import pytest
@@ -1987,6 +1987,30 @@ def test_typing_coercion_defaultdict():
     assert repr(m) == "Model(x=defaultdict(<class 'str'>, {1: '', 'a': ''}))"
 
 
+def test_typing_coercion_counter():
+    class Model(BaseModel):
+        x: Counter[str]
+
+    assert Model.__fields__['x'].type_ is int
+    assert repr(Model(x={'a': 10})) == "Model(x=Counter({'a': 10}))"
+
+
+def test_typing_counter_value_validation():
+    class Model(BaseModel):
+        x: Counter[str]
+
+    with pytest.raises(ValidationError) as exc_info:
+        Model(x={'a': 'a'})
+
+    assert exc_info.value.errors() == [
+        {
+            'loc': ('x', 'a'),
+            'msg': 'value is not a valid integer',
+            'type': 'type_error.integer',
+        }
+    ]
+
+
 def test_class_kwargs_config():
     class Base(BaseModel, extra='forbid', alias_generator=str.upper):
         a: int