Repository: pydantic/pydantic

Issue:
RecursionError when using Literal types in GenericModel
## Bug

If we are trying to use Literal types in GenericModel we are getting `RecursionError: maximum recursion depth exceeded in comparison`.

The minimal code example:
```py
from typing import Literal, Dict, TypeVar, Generic
from pydantic.generics import GenericModel

Fields = Literal['foo', 'bar']

FieldType = TypeVar('FieldType')
ValueType = TypeVar('ValueType')

class GModel(GenericModel, Generic[FieldType, ValueType]):
    field: Dict[FieldType, ValueType]

GModelType = GModel[Fields, str]
```

The traceback:
```
Traceback (most recent call last):
  File "scratch_101.py", line 12, in <module>
    GModelType = GModel[Fields, str]
  File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 110, in __class_getitem__
    {param: None for param in iter_contained_typevars(typevars_map.values())}
  File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 110, in <dictcomp>
    {param: None for param in iter_contained_typevars(typevars_map.values())}
  File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars
    yield from iter_contained_typevars(var)
  File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 220, in iter_contained_typevars
    yield from iter_contained_typevars(arg)
  File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars
    yield from iter_contained_typevars(var)
  File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars
    yield from iter_contained_typevars(var)
  File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars
    yield from iter_contained_typevars(var)
  [Previous line repeated 982 more times]
  File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 214, in iter_contained_typevars
    elif isinstance(v, Iterable):
  File "C:\Programs\Python\Python39_x64\lib\typing.py", line 657, in __instancecheck__
    return self.__subclasscheck__(type(obj))
  File "C:\Programs\Python\Python39_x64\lib\typing.py", line 789, in __subclasscheck__
    return issubclass(cls, self.__origin__)
  File "C:\Programs\Python\Python39_x64\lib\abc.py", line 102, in __subclasscheck__
    return _abc_subclasscheck(cls, subclass)
RecursionError: maximum recursion depth exceeded in comparison
```

----

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
pydantic version: 1.8
        pydantic compiled: True
             install path: /home/esp/.cache/pypoetry/virtualenvs/foobar-n-Q38lsL-py3.9/lib/python3.9/site-packages/pydantic
           python version: 3.9.1 (default, Dec  8 2020, 02:26:20)  [GCC 9.3.0]
                 platform: Linux-4.4.0-19041-Microsoft-x86_64-with-glibc2.31
 optional deps. installed: ['typing-extensions']
```



Discussion:

Resolving patch:
diff --git a/pydantic/generics.py b/pydantic/generics.py
--- a/pydantic/generics.py
+++ b/pydantic/generics.py
@@ -6,7 +6,6 @@
     ClassVar,
     Dict,
     Generic,
-    Iterable,
     Iterator,
     List,
     Mapping,
@@ -205,13 +204,16 @@ def check_parameters_count(cls: Type[GenericModel], parameters: Tuple[Any, ...])
         raise TypeError(f'Too {description} parameters for {cls.__name__}; actual {actual}, expected {expected}')
 
 
+DictValues: Type[Any] = {}.values().__class__
+
+
 def iter_contained_typevars(v: Any) -> Iterator[TypeVarType]:
     """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found."""
     if isinstance(v, TypeVar):
         yield v
     elif hasattr(v, '__parameters__') and not get_origin(v) and lenient_issubclass(v, GenericModel):
         yield from v.__parameters__
-    elif isinstance(v, Iterable):
+    elif isinstance(v, (DictValues, list)):
         for var in v:
             yield from iter_contained_typevars(var)
     else:


Test patch:
diff --git a/tests/test_generics.py b/tests/test_generics.py
--- a/tests/test_generics.py
+++ b/tests/test_generics.py
@@ -3,6 +3,7 @@
 from typing import Any, Callable, ClassVar, Dict, Generic, List, Optional, Sequence, Tuple, Type, TypeVar, Union
 
 import pytest
+from typing_extensions import Literal
 
 from pydantic import BaseModel, Field, ValidationError, root_validator, validator
 from pydantic.generics import GenericModel, _generic_types_cache, iter_contained_typevars, replace_types
@@ -1039,3 +1040,34 @@ class Model2(GenericModel, Generic[T]):
     Model2 = module.Model2
     result = Model1[str].parse_obj(dict(ref=dict(ref=dict(ref=dict(ref=123)))))
     assert result == Model1(ref=Model2(ref=Model1(ref=Model2(ref='123'))))
+
+
+@skip_36
+def test_generic_enum():
+    T = TypeVar('T')
+
+    class SomeGenericModel(GenericModel, Generic[T]):
+        some_field: T
+
+    class SomeStringEnum(str, Enum):
+        A = 'A'
+        B = 'B'
+
+    class MyModel(BaseModel):
+        my_gen: SomeGenericModel[SomeStringEnum]
+
+    m = MyModel.parse_obj({'my_gen': {'some_field': 'A'}})
+    assert m.my_gen.some_field is SomeStringEnum.A
+
+
+@skip_36
+def test_generic_literal():
+    FieldType = TypeVar('FieldType')
+    ValueType = TypeVar('ValueType')
+
+    class GModel(GenericModel, Generic[FieldType, ValueType]):
+        field: Dict[FieldType, ValueType]
+
+    Fields = Literal['foo', 'bar']
+    m = GModel[Fields, str](field={'foo': 'x'})
+    assert m.dict() == {'field': {'foo': 'x'}}