internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: python/mypy

Issue:
isinstance/issubclass don't properly handle tuple of tuples
This code:
```
def f(x: Union[int, str, List, Tuple]) -> None:
    if isinstance(x, (str, (int, tuple))):
        print(x[1])
```
results in error: Argument 2 to "isinstance" has incompatible type "Tuple[str, Tuple[List[_T], Tuple[_T_co, ...]]]"; expected "Union[type, Tuple[type, ...]]".

Python 2 and 3 allow to put nested tuples as the second argument to isinstance, but neither typeshed nor mypy are aware of it. The typeshed needs to be fixed first (python/typeshed#997), but then still some logic needs to be updated inside mypy (otherwise, it results in internal error since it doesn't expect nested tuples; it should instead result in an type validation error).


Discussion:

Resolving patch:
diff --git a/mypy/checker.py b/mypy/checker.py
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -2693,12 +2693,7 @@ def flatten(t: Expression) -> List[Expression]:
 
 
 def get_isinstance_type(expr: Expression, type_map: Dict[Expression, Type]) -> Type:
-    type = type_map[expr]
-
-    if isinstance(type, TupleType):
-        all_types = type.items
-    else:
-        all_types = [type]
+    all_types = [type_map[e] for e in flatten(expr)]
 
     types = []  # type: List[Type]
 


Test patch:
diff --git a/test-data/unit/check-isinstance.test b/test-data/unit/check-isinstance.test
--- a/test-data/unit/check-isinstance.test
+++ b/test-data/unit/check-isinstance.test
@@ -31,6 +31,22 @@ z = [a.y for b in y for a in b]
 
 [builtins fixtures/list.pyi]
 
+[case testIsinstanceNestedTuple]
+from typing import Union, List, Tuple, Dict
+def f(x: Union[int, str, List]) -> None:
+    if isinstance(x, (str, (int,))):
+        reveal_type(x)  # E: Revealed type is 'Union[builtins.int, builtins.str]'
+        x[1]  # E: Value of type "Union[int, str]" is not indexable
+    else:
+        reveal_type(x)  # E: Revealed type is 'builtins.list[Any]'
+        x[1]
+    reveal_type(x)  # E: Revealed type is 'Union[builtins.int, builtins.str, builtins.list[Any]]'
+    if isinstance(x, (str, (list,))):
+        reveal_type(x)  # E: Revealed type is 'Union[builtins.str, builtins.list[Any]]'
+        x[1]
+    reveal_type(x)  # E: Revealed type is 'Union[builtins.int, builtins.str, builtins.list[Any]]'
+[builtins fixtures/isinstancelist.pyi]
+
 [case testClassAttributeInitialization-skip]
 class A:
     x = None # type: int
Repository: python/mypy

Issue:
Direct "super" call of type.__init__ complains about type of first arg
Repro:
```python
class M(type):
    def __init__(cls, name, base, attrs) -> None:
        type.__init__(cls, name, base, attrs)  # E: Argument 1 to "__init__" of "type" has incompatible type "M"; expected "type"
```
This appears to be a regression due to #2825 "Treat type equivalent to Type[Any]; fixes #2655" (@ilevkivskyi, reviewed by @ddfisher).


Discussion:

Resolving patch:
diff --git a/mypy/subtypes.py b/mypy/subtypes.py
--- a/mypy/subtypes.py
+++ b/mypy/subtypes.py
@@ -160,7 +160,14 @@ def visit_instance(self, left: Instance) -> bool:
             item = right.item
             if isinstance(item, TupleType):
                 item = item.fallback
-            return isinstance(item, Instance) and is_subtype(left, item.type.metaclass_type)
+            if isinstance(item, Instance):
+                return is_subtype(left, item.type.metaclass_type)
+            elif isinstance(item, AnyType):
+                # Special case: all metaclasses are subtypes of Type[Any]
+                mro = left.type.mro or []
+                return any(base.fullname() == 'builtins.type' for base in mro)
+            else:
+                return False
         else:
             return False
 


Test patch:
diff --git a/test-data/unit/check-classes.test b/test-data/unit/check-classes.test
--- a/test-data/unit/check-classes.test
+++ b/test-data/unit/check-classes.test
@@ -2217,6 +2217,20 @@ C1[Type[Any]], C2[type] # both these should not fail
 [builtins fixtures/list.pyi]
 [out]
 
+[case testTypeEquivalentTypeAnyEdgeCase]
+class C:
+    pass
+
+class M(type):
+    def __init__(cls, x) -> None:
+        type.__init__(cls, x)
+
+class Mbad(type):
+    def __init__(cls, x) -> None:
+        type.__init__(C(), x) # E: Argument 1 to "__init__" of "type" has incompatible type "C"; expected "type"
+[builtins fixtures/primitives.pyi]
+[out]
+
 [case testTypeMatchesOverloadedFunctions]
 from typing import Type, overload, Union
Repository: python/mypy

Issue:
Dict literal in TypedDict context
A compatible dict literal should be valid if the type context is a typed dict type. Example:

```python
from mypy_extensions import TypedDict

Point = TypedDict('Point', {'x': int, 'y': int})

def f(p: Point) -> None: pass

f({'x': 1, 'y': 3})  # Ok
p = {'x': 2, 'y': 3}  # type: Point  # Ok
```


Discussion:

Resolving patch:
diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py
--- a/mypy/checkexpr.py
+++ b/mypy/checkexpr.py
@@ -1694,6 +1694,18 @@ def visit_dict_expr(self, e: DictExpr) -> Type:
 
         Translate it into a call to dict(), with provisions for **expr.
         """
+        # if the dict literal doesn't match TypedDict, check_typeddict_call_with_dict reports
+        # an error, but returns the TypedDict type that matches the literal it found
+        # that would cause a second error when that TypedDict type is returned upstream
+        # to avoid the second error, we always return TypedDict type that was requested
+        if isinstance(self.type_context[-1], TypedDictType):
+            self.check_typeddict_call_with_dict(
+                callee=self.type_context[-1],
+                kwargs=e,
+                context=e
+            )
+            return self.type_context[-1].copy_modified()
+
         # Collect function arguments, watching out for **expr.
         args = []  # type: List[Expression]  # Regular "key: value"
         stargs = []  # type: List[Expression]  # For "**expr"


Test patch:
diff --git a/test-data/unit/check-typeddict.test b/test-data/unit/check-typeddict.test
--- a/test-data/unit/check-typeddict.test
+++ b/test-data/unit/check-typeddict.test
@@ -610,3 +610,42 @@ def f() -> None:
     A = TypedDict('A', {'x': int})
 A  # E: Name 'A' is not defined
 [builtins fixtures/dict.pyi]
+
+
+-- Use dict literals
+
+[case testTypedDictDictLiterals]
+from mypy_extensions import TypedDict
+
+Point = TypedDict('Point', {'x': int, 'y': int})
+
+def f(p: Point) -> None:
+    p = {'x': 2, 'y': 3}
+    p = {'x': 2}  # E: Expected items ['x', 'y'] but found ['x'].
+    p = dict(x=2, y=3)
+
+f({'x': 1, 'y': 3})
+f({'x': 1, 'y': 'z'})  # E: Incompatible types (expression has type "str", TypedDict item "y" has type "int")
+
+f(dict(x=1, y=3))
+f(dict(x=1, y=3, z=4))  # E: Expected items ['x', 'y'] but found ['x', 'y', 'z'].
+
+[builtins fixtures/dict.pyi]
+
+
+[case testTypedDictExplicitTypes]
+from mypy_extensions import TypedDict
+
+Point = TypedDict('Point', {'x': int, 'y': int})
+
+p1: Point = {'x': 'hi'}  # E: Expected items ['x', 'y'] but found ['x'].
+
+p2: Point
+p2 = dict(x='bye')  # E: Expected items ['x', 'y'] but found ['x'].
+
+p3 = Point(x=1, y=2)
+p3 = {'x': 'hi'}  # E: Expected items ['x', 'y'] but found ['x'].
+
+p4: Point = {'x': 1, 'y': 2}
+
+[builtins fixtures/dict.pyi]
Repository: python/mypy

Issue:
Bug with `type: ignore` comment on import and incremental
Still trying to get a test case. However, for now, I'll post the interesting parts:
- In `errors.py`, I have code like this:

``` python
import colorama  # type: ignore
```

For some reason, the cache for this file at some point didn't add `colorama` to the `suppressed` section, so the import started being an error.



Discussion:
Hm, interesting. @Michael0x2a might have some insights.

Create the following files:
- `x.py`:
  
  ``` python
  A = 0
  from y import B
  ```
- `y.py`:
  
  ``` python
  import xyz  # type: ignore
  B = 0
  from x import A
  ```

Now, watch the following commands:

```
ryan@DevPC-LX ~/blaze-mypy/bug master $ mypy -i x.py  # Works.
ryan@DevPC-LX ~/blaze-mypy/bug master $ touch x.py    # Update the mtime of x.py.
ryan@DevPC-LX ~/blaze-mypy/bug master $ mypy -i x.py  # Works.
ryan@DevPC-LX ~/blaze-mypy/bug master $ touch x.py    # Update the mtime of x.py again.
ryan@DevPC-LX ~/blaze-mypy/bug master $ mypy -i x.py  # Fails!
x.py:2: note: In module imported here:
y.py:1: error: Cannot find module named 'xyz'
y.py:1: note: (Perhaps setting MYPYPATH or using the "--silent-imports" flag would help)
ryan@DevPC-LX ~/blaze-mypy/bug master $ 
```

Workaround to avoid having to clear the _entire_ cache: `rm .mypy_cache/*/y.*.json`, replacing `y` with the module that had the `type: ignore` comment.

Workarounds for incremental mode that requires deleting cache files are not
very useful. :-)

Well, I actually just realized that a much, much better workaround is to just do `touch y.py`... I don't know why I didn't think of that before...

But it definitely is a bug.

Is this still reproducible?
@gvanrossum Yup.

Resolving patch:
diff --git a/mypy/build.py b/mypy/build.py
--- a/mypy/build.py
+++ b/mypy/build.py
@@ -1647,7 +1647,9 @@ def load_graph(sources: List[BuildSource], manager: BuildManager) -> Graph:
             # so we ignore any suppressed module not explicitly re-included
             # from the command line.
             ignored = dep in st.suppressed and dep not in entry_points
-            if dep not in graph and not ignored:
+            if ignored:
+                manager.missing_modules.add(dep)
+            elif dep not in graph:
                 try:
                     if dep in st.ancestors:
                         # TODO: Why not 'if dep not in st.dependencies' ?


Test patch:
Repository: python/mypy

Issue:
Indexing Enum type objects fails sometimes
Assume this definition of `Color`:

```
from enum import Enum
class Color(Enum):
    red = 1
    green = 2
    blue = 3
```

`Color['red']` works, and 'val : Color = Color['red']` both work, but `val = Color['red']` does not work:
```
error: Name 'red' is not defined
error: "Color" expects no type arguments, but 1 given
```

Reference #741


Discussion:
Whoops, yes, definitely a bug. Not sure yet how to fix it.

Resolving patch:
diff --git a/mypy/semanal.py b/mypy/semanal.py
--- a/mypy/semanal.py
+++ b/mypy/semanal.py
@@ -1016,6 +1016,8 @@ def analyze_base_classes(self, defn: ClassDef) -> None:
         # the MRO. Fix MRO if needed.
         if info.mro and info.mro[-1].fullname() != 'builtins.object':
             info.mro.append(self.object_type().type)
+        if defn.info.is_enum and defn.type_vars:
+            self.fail("Enum class cannot be generic", defn)
 
     def expr_to_analyzed_type(self, expr: Expression) -> Type:
         if isinstance(expr, CallExpr):
diff --git a/mypy/typeanal.py b/mypy/typeanal.py
--- a/mypy/typeanal.py
+++ b/mypy/typeanal.py
@@ -61,6 +61,10 @@ def analyze_type_alias(node: Expression,
                     base.fullname in type_constructors or
                     base.kind == TYPE_ALIAS):
                 return None
+            # Enums can't be generic, and without this check we may incorrectly interpret indexing
+            # an Enum class as creating a type alias.
+            if isinstance(base.node, TypeInfo) and base.node.is_enum:
+                return None
         else:
             return None
     else:


Test patch:
diff --git a/test-data/unit/check-enum.test b/test-data/unit/check-enum.test
--- a/test-data/unit/check-enum.test
+++ b/test-data/unit/check-enum.test
@@ -150,9 +150,37 @@ main:5: error: Revealed type is '__main__.E'
 from enum import IntEnum
 class E(IntEnum):
     a = 1
-E[1]
-[out]
-main:4: error: Enum index should be a string (actual index type "int")
+E[1]  # E: Enum index should be a string (actual index type "int")
+x = E[1]  # E: Enum index should be a string (actual index type "int")
+
+[case testEnumIndexIsNotAnAlias]
+from enum import Enum
+
+class E(Enum):
+    a = 1
+    b = 2
+reveal_type(E['a'])  # E: Revealed type is '__main__.E'
+E['a']
+x = E['a']
+reveal_type(x)  # E: Revealed type is '__main__.E'
+
+def get_member(name: str) -> E:
+    val = E[name]
+    return val
+
+reveal_type(get_member('a'))  # E: Revealed type is '__main__.E'
+
+[case testGenericEnum]
+from enum import Enum
+from typing import Generic, TypeVar
+
+T = TypeVar('T')
+
+class F(Generic[T], Enum):  # E: Enum class cannot be generic
+    x: T
+    y: T
+
+reveal_type(F[int].x)  # E: Revealed type is '__main__.F[builtins.int*]'
 
 [case testEnumFlag]
 from enum import Flag
Repository: python/mypy

Issue:
Crash on incorrect number of arguments in `isinstance`
```
if isinstance(int):
    ...
```
causes internal error in mypy:

```
  ...
  File "d:\download\mypy\mypy\checker.py", line 2701, in find_isinstance_check
    types = get_isinstance_type(node.args[1], type_map)
IndexError: list index out of range
```


Discussion:

Resolving patch:
diff --git a/mypy/checker.py b/mypy/checker.py
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -2695,6 +2695,8 @@ def find_isinstance_check(node: Expression,
         return None, {}
     elif isinstance(node, CallExpr):
         if refers_to_fullname(node.callee, 'builtins.isinstance'):
+            if len(node.args) != 2:  # the error will be reported later
+                return {}, {}
             expr = node.args[0]
             if expr.literal == LITERAL_TYPE:
                 vartype = type_map[expr]


Test patch:
Repository: python/mypy

Issue:
Frequent crashes in --quick mode
We're observing frequent crashes in --quick mode on our internal codebase. I haven't debugged this yet, but I have a hunch it has something to do with files containing errors.


Discussion:

Resolving patch:
diff --git a/mypy/subtypes.py b/mypy/subtypes.py
--- a/mypy/subtypes.py
+++ b/mypy/subtypes.py
@@ -135,11 +135,14 @@ def visit_instance(self, left: Instance) -> bool:
         if isinstance(right, TupleType) and right.fallback.type.is_enum:
             return is_subtype(left, right.fallback)
         if isinstance(right, Instance):
-            for base in left.type.mro:
-                if base._promote and is_subtype(
-                        base._promote, self.right, self.check_type_parameter,
-                        ignore_pos_arg_names=self.ignore_pos_arg_names):
-                    return True
+            # NOTO: left.type.mro may be None in quick mode if there
+            # was an error somewhere.
+            if left.type.mro is not None:
+                for base in left.type.mro:
+                    if base._promote and is_subtype(
+                            base._promote, self.right, self.check_type_parameter,
+                            ignore_pos_arg_names=self.ignore_pos_arg_names):
+                        return True
             rname = right.type.fullname()
             if not left.type.has_base(rname) and rname != 'builtins.object':
                 return False


Test patch:
Repository: python/mypy

Issue:
Keyword arguments of __call__ are not interpreted correctly
I looks like mypy drops all keyword arguments of the `__call__` function of a class and recognises only positional arguments.

Code example:

```
class Formatter:
    def __call__(
        self,
        message: str,
        *,  # same behaviour with and without 
        bold: bool = False,
    ) -> str:
        if bold:
            message = f"** {message} **"
        return message

formatter = Formatter()
print(formatter("test", bold=True))
```

Mypy error:
`test.py:13: error: Unexpected keyword argument "bold" for "__call__" of "Formatter"`


Discussion:
Yes, confirmed and seems specific to `__call__`.
Adding ``__call__`` to ``MAGIC_METHODS_ALLOWING_KWARGS`` in ``sharedparse.py`` fixes the issue. I wonder why it is not there now, do older versions of Python not allow kwargs in ``__call__``?
I assume it was just an oversight. Do the tests pass with that one change? Then it's worth adding a test specifically for `__call__` with kwargs and push a PR.

Resolving patch:
diff --git a/mypy/sharedparse.py b/mypy/sharedparse.py
--- a/mypy/sharedparse.py
+++ b/mypy/sharedparse.py
@@ -87,6 +87,7 @@
     "__init__",
     "__init_subclass__",
     "__new__",
+    "__call__",
 }
 
 MAGIC_METHODS_POS_ARGS_ONLY = MAGIC_METHODS - MAGIC_METHODS_ALLOWING_KWARGS


Test patch:
diff --git a/test-data/unit/check-kwargs.test b/test-data/unit/check-kwargs.test
--- a/test-data/unit/check-kwargs.test
+++ b/test-data/unit/check-kwargs.test
@@ -258,6 +258,28 @@ class A: pass
 class B: pass
 [builtins fixtures/dict.pyi]
 
+[case testKwargsAllowedInDunderCall]
+class Formatter:
+    def __call__(self, message: str, bold: bool = False) -> str:
+        pass
+
+formatter = Formatter()
+formatter("test", bold=True)
+reveal_type(formatter.__call__)  # E: Revealed type is 'def (message: builtins.str, bold: builtins.bool =) -> builtins.str'
+[builtins fixtures/bool.pyi]
+[out]
+
+[case testKwargsAllowedInDunderCallKwOnly]
+class Formatter:
+    def __call__(self, message: str, *, bold: bool = False) -> str:
+        pass
+
+formatter = Formatter()
+formatter("test", bold=True)
+reveal_type(formatter.__call__)  # E: Revealed type is 'def (message: builtins.str, *, bold: builtins.bool =) -> builtins.str'
+[builtins fixtures/bool.pyi]
+[out]
+
 [case testInvalidTypeForKeywordVarArg]
 from typing import Dict
 def f( **kwargs: 'A') -> None: pass
Repository: python/mypy

Issue:
Incremental crash caused by TypedDict deserialization
When type checking `t.py` twice using `-i`, the second run crashes:

```py
# t.py
from b import A
y: A
reveal_type(y)
```

```py
# b.py
from mypy_extensions import TypedDict
A = TypedDict('A', {'x': int, 'y': str})
```

I already have a fix in a local branch and I will send a PR soon.


Discussion:

Resolving patch:
diff --git a/mypy/fixup.py b/mypy/fixup.py
--- a/mypy/fixup.py
+++ b/mypy/fixup.py
@@ -64,6 +64,8 @@ def visit_type_info(self, info: TypeInfo) -> None:
                 info._promote.accept(self.type_fixer)
             if info.tuple_type:
                 info.tuple_type.accept(self.type_fixer)
+            if info.typeddict_type:
+                info.typeddict_type.accept(self.type_fixer)
         finally:
             self.current_info = save_info
 


Test patch:
diff --git a/test-data/unit/check-incremental.test b/test-data/unit/check-incremental.test
--- a/test-data/unit/check-incremental.test
+++ b/test-data/unit/check-incremental.test
@@ -1907,6 +1907,23 @@ a.A().x = 0
 [out2]
 tmp/b.py:2: error: Cannot assign to class variable "x" via instance
 
+[case testSerializeTypedDict]
+import b
+reveal_type(b.x)
+y: b.A
+reveal_type(y)
+[file b.py]
+from mypy_extensions import TypedDict
+A = TypedDict('A', {'x': int, 'y': str})
+x: A
+[builtins fixtures/dict.pyi]
+[out1]
+main:2: error: Revealed type is 'TypedDict(x=builtins.int, y=builtins.str, _fallback=b.A)'
+main:4: error: Revealed type is 'TypedDict(x=builtins.int, y=builtins.str, _fallback=b.A)'
+[out2]
+main:2: error: Revealed type is 'TypedDict(x=builtins.int, y=builtins.str, _fallback=b.A)'
+main:4: error: Revealed type is 'TypedDict(x=builtins.int, y=builtins.str, _fallback=b.A)'
+
 [case testQuickAndDirty1]
 # flags: --quick-and-dirty
 import b, c
Repository: python/mypy

Issue:
isinstance check does not narrow inferred type correctly on nested Union type
```py
from typing import Union

class A: pass
class B: pass
class C: pass

def foo(bar: Union[Union[A, B], C]) -> None:
    if isinstance(bar, A):
        reveal_type(bar)
    else:
        reveal_type(bar)
```
The last line reveals `Union[A, B, C]` when it should be just `Union[B, C]`. It works if the type of `bar` is replaced by `Union[A, B, C]`.

(Of course you'd probably never directly write `Union[Union[A, B], C]`, but it's reasonable to write `Union[AB, C]` where `AB` is an alias for `Union[A, B]`. And the typing module documentation says [Unions of Unions are flattened](https://docs.python.org/3/library/typing.html#typing.Union).)


Discussion:
Is this still failing on master?
Yes, I just checked this. Probably this is because interaction of ``restrict_subtype_away`` and ``is_proper_subtype`` misses the case of nested unions.

Resolving patch:
diff --git a/mypy/types.py b/mypy/types.py
--- a/mypy/types.py
+++ b/mypy/types.py
@@ -987,7 +987,7 @@ class UnionType(Type):
     items = None  # type: List[Type]
 
     def __init__(self, items: List[Type], line: int = -1, column: int = -1) -> None:
-        self.items = items
+        self.items = flatten_nested_unions(items)
         self.can_be_true = any(item.can_be_true for item in items)
         self.can_be_false = any(item.can_be_false for item in items)
         super().__init__(line, column)
@@ -1732,6 +1732,17 @@ def get_type_vars(typ: Type) -> List[TypeVarType]:
     return tvars
 
 
+def flatten_nested_unions(types: Iterable[Type]) -> List[Type]:
+    """Flatten nested unions in a type list."""
+    flat_items = []  # type: List[Type]
+    for tp in types:
+        if isinstance(tp, UnionType):
+            flat_items.extend(flatten_nested_unions(tp.items))
+        else:
+            flat_items.append(tp)
+    return flat_items
+
+
 def union_items(typ: Type) -> List[Type]:
     """Return the flattened items of a union type.
 


Test patch:
diff --git a/test-data/unit/check-unions.test b/test-data/unit/check-unions.test
--- a/test-data/unit/check-unions.test
+++ b/test-data/unit/check-unions.test
@@ -453,6 +453,21 @@ reveal_type(l) \
     # E: Revealed type is 'builtins.list[Union[builtins.bool, builtins.int, builtins.float, builtins.str]]'
 [builtins fixtures/list.pyi]
 
+[case testNestedUnionsProcessedCorrectly]
+from typing import Union
+
+class A: pass
+class B: pass
+class C: pass
+
+def foo(bar: Union[Union[A, B], C]) -> None:
+    if isinstance(bar, A):
+        reveal_type(bar)  # E: Revealed type is '__main__.A'
+    else:
+        reveal_type(bar)  # E: Revealed type is 'Union[__main__.B, __main__.C]'
+[builtins fixtures/isinstance.pyi]
+[out]
+
 [case testAssignAnyToUnion]
 from typing import Union, Any
 x: Union[int, str]