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

Issue:
Right 'is' operand not type checked
Mypy produces no error for this program, even though it clearly should:
```py
1 is 1()
```


Discussion:

Resolving patch:
diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py
--- a/mypy/checkexpr.py
+++ b/mypy/checkexpr.py
@@ -1395,7 +1395,7 @@ def visit_comparison_expr(self, e: ComparisonExpr) -> Type:
             method_type = None  # type: Optional[mypy.types.Type]
 
             if operator == 'in' or operator == 'not in':
-                right_type = self.accept(right)  # TODO only evaluate if needed
+                right_type = self.accept(right)  # always validate the right operand
 
                 # Keep track of whether we get type check errors (these won't be reported, they
                 # are just to verify whether something is valid typing wise).
@@ -1429,6 +1429,7 @@ def visit_comparison_expr(self, e: ComparisonExpr) -> Type:
                                                     allow_reverse=True)
 
             elif operator == 'is' or operator == 'is not':
+                self.accept(right)  # validate the right operand
                 sub_result = self.bool_type()
                 method_type = None
             else:


Test patch:
diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test
--- a/test-data/unit/check-expressions.test
+++ b/test-data/unit/check-expressions.test
@@ -613,6 +613,13 @@ class A: pass
 [out]
 main:3: error: Incompatible types in assignment (expression has type "bool", variable has type "A")
 
+[case testIsRightOperand]
+
+1 is 1()
+[builtins fixtures/bool.pyi]
+[out]
+main:2: error: "int" not callable
+
 [case testReverseBinaryOperator]
 
 class A:
Repository: python/mypy

Issue:
Semantic analysis error not reported within lambda
This doesn't generate an error, though it's clearly invalid:

```py
lambda: xyz
```

This generates an error:

```py
lambda: 1 + ''
```

It looks like type checking errors are reported within a lambda but semantic analysis errors are lost. 

This is not a regression -- this bug has been around for a long time.


Discussion:

Resolving patch:
diff --git a/mypy/nodes.py b/mypy/nodes.py
--- a/mypy/nodes.py
+++ b/mypy/nodes.py
@@ -1480,6 +1480,9 @@ def expr(self) -> Expression:
     def accept(self, visitor: ExpressionVisitor[T]) -> T:
         return visitor.visit_lambda_expr(self)
 
+    def is_dynamic(self) -> bool:
+        return False
+
 
 class ListExpr(Expression):
     """List literal expression [...]."""


Test patch:
diff --git a/test-data/unit/check-functions.test b/test-data/unit/check-functions.test
--- a/test-data/unit/check-functions.test
+++ b/test-data/unit/check-functions.test
@@ -2212,3 +2212,19 @@ def i() -> List[Union[str, int]]:
     return x
 
 [builtins fixtures/dict.pyi]
+
+[case testLambdaSemanal]
+f = lambda: xyz
+[out]
+main:1: error: Name 'xyz' is not defined
+
+[case testLambdaTypeCheck]
+f = lambda: 1 + '1'
+[out]
+main:1: error: Unsupported operand types for + ("int" and "str")
+
+[case testLambdaTypeInference]
+f = lambda: 5
+reveal_type(f)
+[out]
+main:2: error: Revealed type is 'def () -> builtins.int'
\ No newline at end of file
Repository: python/mypy

Issue:
mypy_extensions: missing dependency? typing (py27)
```
(mypytest) [root@80ca205d2ef4 recipe]# pip install mypy_extensions
Collecting mypy_extensions
  Downloading mypy_extensions-0.3.0.tar.gz
Building wheels for collected packages: mypy-extensions
  Running setup.py bdist_wheel for mypy-extensions ... done
  Stored in directory: /root/.cache/pip/wheels/58/47/b8/ffdcbc1959691d5ff42fa78937b36638ccbed59f2af8d35b18
Successfully built mypy-extensions
Installing collected packages: mypy-extensions
Successfully installed mypy-extensions-0.3.0
(mypytest) [root@80ca205d2ef4 recipe]# python -c "import mypy_extensions"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/opt/conda/envs/mypytest/lib/python2.7/site-packages/mypy_extensions.py", line 8, in <module>
    from typing import Any
ImportError: No module named typing
```


Discussion:
It seems pretty silly to be using mypy_extensions without typing, but you're right, this should be added to extensions/setup.py. Can you submit a PR to add it?

Resolving patch:
diff --git a/extensions/setup.py b/extensions/setup.py
--- a/extensions/setup.py
+++ b/extensions/setup.py
@@ -40,4 +40,7 @@
     platforms=['POSIX'],
     py_modules=['mypy_extensions'],
     classifiers=classifiers,
+    install_requires=[
+        'typing >= 3.5.3; python_version < "3.5"',
+    ],
 )


Test patch:
Repository: python/mypy

Issue:
Strange "Returning Any" warning
`mypy --warn-return-any` (ver. 0.550) gives a strange "Returning Any from function ..." warning for the following code:
```
def f(a: 'A') -> int:
    if a._x == 2:
        return 2
    n = 1
    return n

class A:
    def __init__(self) -> None:
        self._x = 2
```
```
foo.py:5: warning: Returning Any from function declared to return "int"
```
Combining `n = 1` `return n` into one statement `return 1` or putting the definition of `A` before `f` makes the warning disappear.


Discussion:

Resolving patch:
diff --git a/mypy/checker.py b/mypy/checker.py
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -2133,7 +2133,7 @@ def check_return_stmt(self, s: ReturnStmt) -> None:
                 if isinstance(typ, AnyType):
                     # (Unless you asked to be warned in that case, and the
                     # function is not declared to return Any)
-                    if (self.options.warn_return_any and
+                    if (self.options.warn_return_any and not self.current_node_deferred and
                             not is_proper_subtype(AnyType(TypeOfAny.special_form), return_type)):
                         self.msg.incorrectly_returning_any(return_type, s)
                     return


Test patch:
diff --git a/test-data/unit/check-warnings.test b/test-data/unit/check-warnings.test
--- a/test-data/unit/check-warnings.test
+++ b/test-data/unit/check-warnings.test
@@ -197,3 +197,15 @@ class Test(object):
             return None
 [builtins fixtures/list.pyi]
 [out]
+
+[case testReturnAnyDeferred]
+# flags: --warn-return-any
+def foo(a1: A) -> int:
+    if a1._x:
+        return 1
+    n = 1
+    return n
+
+class A:
+    def __init__(self, x: int) -> None:
+        self._x = x
Repository: python/mypy

Issue:
Produce better error on invalid types like List(int)
Fixes #4172


Discussion:
Added some more tests, including a python3 one (the existing one was already python2).

I'm taking a look at the other issues mentioned in the bug and will put up another PR for them.


Resolving patch:
diff --git a/mypy/fastparse.py b/mypy/fastparse.py
--- a/mypy/fastparse.py
+++ b/mypy/fastparse.py
@@ -157,6 +157,9 @@ def __init__(self,
         self.is_stub = is_stub
         self.errors = errors
 
+    def note(self, msg: str, line: int, column: int) -> None:
+        self.errors.report(line, column, msg, severity='note')
+
     def fail(self, msg: str, line: int, column: int) -> None:
         self.errors.report(line, column, msg)
 
@@ -356,6 +359,9 @@ def do_func_def(self, n: Union[ast3.FunctionDef, ast3.AsyncFunctionDef],
                     arg_types.insert(0, AnyType(TypeOfAny.special_form))
             except SyntaxError:
                 self.fail(TYPE_COMMENT_SYNTAX_ERROR, n.lineno, n.col_offset)
+                if n.type_comment and n.type_comment[0] != "(":
+                    self.note('Suggestion: wrap argument types in parentheses',
+                              n.lineno, n.col_offset)
                 arg_types = [AnyType(TypeOfAny.from_error)] * len(args)
                 return_type = AnyType(TypeOfAny.from_error)
         else:


Test patch:
diff --git a/test-data/unit/check-fastparse.test b/test-data/unit/check-fastparse.test
--- a/test-data/unit/check-fastparse.test
+++ b/test-data/unit/check-fastparse.test
@@ -14,10 +14,16 @@ x = None # type: a + b  # E: invalid type comment or annotation
 -- This happens in both parsers.
 [case testFastParseFunctionAnnotationSyntaxError]
 
-def f():  # E: syntax error in type comment
+def f():  # E: syntax error in type comment # N: Suggestion: wrap argument types in parentheses
   # type: None -> None
   pass
 
+[case testFastParseFunctionAnnotationSyntaxErrorSpaces]
+
+def f():  # E: syntax error in type comment # N: Suggestion: wrap argument types in parentheses
+  # type:             None -> None
+  pass
+
 [case testFastParseInvalidFunctionAnnotation]
 
 def f(x):  # E: invalid type comment or annotation
diff --git a/test-data/unit/parse-errors.test b/test-data/unit/parse-errors.test
--- a/test-data/unit/parse-errors.test
+++ b/test-data/unit/parse-errors.test
@@ -169,6 +169,7 @@ def f(): # type: x
   pass
 [out]
 file:1: error: syntax error in type comment
+file:1: note: Suggestion: wrap argument types in parentheses
 
 [case testInvalidSignatureInComment2]
 def f(): # type:
Repository: python/mypy

Issue:
NamedTuple subclasses are not considered callable even when they have a __call__ method
```
from typing import Tuple, NamedTuple

Thing = NamedTuple('Thing', [('s', str), ('n', int)])

class CallableTuple(Thing):
    def __call__(self) -> str:
        return self.s + str(self.n)

o = CallableTuple('hello ', 12)
print(o())
```
produces the message
```error: "CallableTuple" not callable```


Discussion:
This one is easy, just add another ``elif`` for ``TupleType`` in ``checkexpr.check_call`` that just calls ``check_call`` on tuple ``fallback``

Resolving patch:
diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py
--- a/mypy/checkexpr.py
+++ b/mypy/checkexpr.py
@@ -639,6 +639,10 @@ def check_call(self, callee: Type, args: List[Expression],
             item = self.analyze_type_type_callee(callee.item, callee)
             return self.check_call(item, args, arg_kinds, context, arg_names,
                                    callable_node, arg_messages)
+        elif isinstance(callee, TupleType):
+            return self.check_call(callee.fallback, args, arg_kinds, context,
+                                   arg_names, callable_node, arg_messages, callable_name,
+                                   object_type)
         else:
             return self.msg.not_callable(callee, context), AnyType(TypeOfAny.from_error)
 


Test patch:
diff --git a/test-data/unit/check-namedtuple.test b/test-data/unit/check-namedtuple.test
--- a/test-data/unit/check-namedtuple.test
+++ b/test-data/unit/check-namedtuple.test
@@ -649,3 +649,16 @@ d: Type[D]
 d.g()  # E: "Type[D]" has no attribute "g"
 d.f()
 [builtins fixtures/classmethod.pyi]
+
+[case testTypeNamedTupleCall]
+
+from typing import NamedTuple
+
+Thing = NamedTuple('Thing', [('s', str), ('n', int)])
+
+class CallableTuple(Thing):
+    def __call__(self) -> None:
+        pass
+
+o = CallableTuple('hello ', 12)
+o()
diff --git a/test-data/unit/check-tuples.test b/test-data/unit/check-tuples.test
--- a/test-data/unit/check-tuples.test
+++ b/test-data/unit/check-tuples.test
@@ -967,3 +967,16 @@ t: Type[C]
 t.g()  # E: "Type[C]" has no attribute "g"
 t.f()
 [builtins fixtures/classmethod.pyi]
+
+[case testTypeTupleCall]
+from typing import Tuple
+
+def foo(o: CallableTuple) -> int:
+    reveal_type(o)  # E: Revealed type is 'Tuple[builtins.str, builtins.int, fallback=__main__.CallableTuple]'
+    return o(1, 2)
+
+class CallableTuple(Tuple[str, int]):
+    def __call__(self, n: int, m: int) -> int:
+        return n
+
+[builtins fixtures/tuple.pyi]
Repository: python/mypy

Issue:
Forward reference to decorated class method has type Any
In the program below, the type inferred for `cls.g` in `A.f` is `Any`, even though it should be `def (x: builtins.str)`:


```py
from typing import TypeVar, Callable

T = TypeVar('T')
def dec() -> Callable[[T], T]: pass

class A:
    @classmethod
    def f(cls) -> None:
        reveal_type(cls.g)  # Any  <-- unexpected

    @classmethod
    @dec()
    def g(cls, x: str) -> None:
        pass

    @classmethod
    def h(cls) -> None:
        reveal_type(cls.g)  # def (x: builtins.str)  <-- ok
```

This works correctly when the decorated method is accessed using an instance type (such as `self`).

In fine-grained incremental mode the types can be more precise, which can result in additional errors in fine-grained incremental mode.


Discussion:

Resolving patch:
diff --git a/mypy/checkmember.py b/mypy/checkmember.py
--- a/mypy/checkmember.py
+++ b/mypy/checkmember.py
@@ -467,8 +467,12 @@ def analyze_class_attribute_access(itype: Instance,
         return builtin_type('types.ModuleType')
 
     if is_decorated:
-        # TODO: Return type of decorated function. This is quick hack to work around #998.
-        return AnyType(TypeOfAny.special_form)
+        assert isinstance(node.node, Decorator)
+        if node.node.type:
+            return node.node.type
+        else:
+            not_ready_callback(name, context)
+            return AnyType(TypeOfAny.from_error)
     else:
         return function_type(cast(FuncBase, node.node), builtin_type('builtins.function'))
 


Test patch:
diff --git a/test-data/unit/check-inference.test b/test-data/unit/check-inference.test
--- a/test-data/unit/check-inference.test
+++ b/test-data/unit/check-inference.test
@@ -1786,6 +1786,31 @@ y = 0
 tmp/m.py:2: error: "int" not callable
 main:3: error: "int" not callable
 
+[case testForwardReferenceToDecoratedClassMethod]
+from typing import TypeVar, Callable
+
+T = TypeVar('T')
+def dec() -> Callable[[T], T]: pass
+
+A.g  # E: Cannot determine type of 'g'
+
+class A:
+    @classmethod
+    def f(cls) -> None:
+        reveal_type(cls.g)  # E: Revealed type is 'def (x: builtins.str)'
+
+    @classmethod
+    @dec()
+    def g(cls, x: str) -> None:
+        pass
+
+    @classmethod
+    def h(cls) -> None:
+        reveal_type(cls.g)  # E: Revealed type is 'def (x: builtins.str)'
+
+reveal_type(A.g)  # E: Revealed type is 'def (x: builtins.str)'
+[builtins fixtures/classmethod.pyi]
+
 
 -- Tests for special cases of unification
 -- --------------------------------------
Repository: python/mypy

Issue:
Spurious complaint about return value in deferred function
Mypy incorrectly complains about the return statement in this program (with `--strict-optional`):

```py
def f() -> str:
    y  # Causes f to be deferred
    x = None
    if int():
        x = ''
    if x is None:
        x = ''
    return x  # Incompatible return value type (got "Optional[Any]", expected "str")

y = int()
```

The expected behavior is clean output.

Note that `f` is deferred. The problem goes away when `f` is not deferred.


Discussion:
Slightly tweaked example illustrates another problem:

```py
def f() -> str:
    y
    x = None
    if int():
        x = ''
    if x is None:
        x = ''
        x[0]  # Value of type "None" is not indexable   <-- Unexpected
    return x  # Incompatible return value type (got "Optional[Any]", expected "str")

y = int()
```

Resolving patch:
diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py
--- a/mypy/checkexpr.py
+++ b/mypy/checkexpr.py
@@ -2595,7 +2595,11 @@ def bool_type(self) -> Instance:
     def narrow_type_from_binder(self, expr: Expression, known_type: Type) -> Type:
         if literal(expr) >= LITERAL_TYPE:
             restriction = self.chk.binder.get(expr)
-            if restriction:
+            # If the current node is deferred, some variables may get Any types that they
+            # otherwise wouldn't have. We don't want to narrow down these since it may
+            # produce invalid inferred Optional[Any] types, at least.
+            if restriction and not (isinstance(known_type, AnyType)
+                                    and self.chk.current_node_deferred):
                 ans = narrow_declared_type(known_type, restriction)
                 return ans
         return known_type


Test patch:
diff --git a/test-data/unit/check-optional.test b/test-data/unit/check-optional.test
--- a/test-data/unit/check-optional.test
+++ b/test-data/unit/check-optional.test
@@ -673,3 +673,19 @@ class A:
         lambda: (self.y, x.a) # E: Cannot determine type of 'y'
         self.y = int()
 [builtins fixtures/isinstancelist.pyi]
+
+[case testDeferredAndOptionalInferenceSpecialCase]
+def f() -> str:
+    y
+    x = None
+    if int():
+        x = ''
+    if x is None:
+        x = ''
+        g(x)
+    return x
+
+def g(x: str) -> None: pass
+
+y = int()
+[builtins fixtures/bool.pyi]
Repository: python/mypy

Issue:
Spurious "Cannot determine type of 'x'" in fine-grained incremental mode
The following test case fails in fine-grained incremental mode though it should pass:

```
[case testInferAttributeTypeAndMultipleStaleTargets]
import a

class A:
    def g(self) -> None:
        a.x
        self.x = 1

    def f(self) -> None:
        a.x
        a = self.x
        self.x = 1

[file a.py]
x = 0
[file a.py.2]
x = ''
[out]
==
```

Here's the actual output:

```
==
main:10: error: Cannot determine type of 'x'
```

Switching the names of the methods (`g` <-> `f`) works around the failure. The apparent reason for the failure is that we sort targets to process within a file by string value when propagating changes, so `f` gets processed before `g`. The correct way to sort targets is by line number.


Discussion:

Resolving patch:
diff --git a/mypy/server/update.py b/mypy/server/update.py
--- a/mypy/server/update.py
+++ b/mypy/server/update.py
@@ -809,20 +809,12 @@ def reprocess_nodes(manager: BuildManager,
     old_symbols = find_symbol_tables_recursive(file_node.fullname(), file_node.names)
     old_symbols = {name: names.copy() for name, names in old_symbols.items()}
 
-    def key(node: DeferredNode) -> str:
-        fullname = node.node.fullname()
-        if fullname is None:
-            if isinstance(node.node, FuncDef):
-                info = node.node.info
-            elif isinstance(node.node, OverloadedFuncDef):
-                info = node.node.items[0].info
-            else:
-                assert False, "'None' fullname for %s instance" % type(node.node)
-            assert info is not None
-            fullname = '%s.%s' % (info.fullname(), node.node.name())
-        return fullname
+    def key(node: DeferredNode) -> int:
+        # Unlike modules which are sorted by name within SCC,
+        # nodes within the same module are sorted by line number, because
+        # this is how they are processed in normal mode.
+        return node.node.line
 
-    # Sort nodes by full name so that the order of processing is deterministic.
     nodes = sorted(nodeset, key=key)
 
     # TODO: ignore_all argument to set_file_ignored_lines


Test patch:
diff --git a/test-data/unit/fine-grained.test b/test-data/unit/fine-grained.test
--- a/test-data/unit/fine-grained.test
+++ b/test-data/unit/fine-grained.test
@@ -1564,6 +1564,26 @@ class C:
 main:5: error: Too few arguments for "__init__" of "C"
 main:6: error: Too few arguments for "D"
 
+[case testInferAttributeTypeAndMultipleStaleTargets]
+import a
+
+class A:
+    def g(self) -> None:
+        a.x
+        self.x = 1
+
+    def f(self) -> None:
+        a.x
+        b = self.x
+        self.x = 1
+
+[file a.py]
+x = 0
+[file a.py.2]
+x = ''
+[out]
+==
+
 [case testNamedTupleUpdate]
 import b
 [file a.py]
Repository: python/mypy

Issue:
stubgen may generate (*args, *, ...)
I ran stubgen recursively on the asyncio package, and found this in the output:
```py
    def subprocess_exec(self, protocol_factory, program, *args, *, stdin: Any = ..., stdout: Any = ..., stderr: Any = ..., universal_newlines: bool = ..., shell: bool = ..., bufsize: int = ..., **kwargs): ...
```


Discussion:

Resolving patch:
diff --git a/mypy/stubgen.py b/mypy/stubgen.py
--- a/mypy/stubgen.py
+++ b/mypy/stubgen.py
@@ -457,7 +457,8 @@ def visit_func_def(self, o: FuncDef) -> None:
                 annotation = ""
             if arg_.initializer:
                 initializer = '...'
-                if kind in (ARG_NAMED, ARG_NAMED_OPT) and '*' not in args:
+                if kind in (ARG_NAMED, ARG_NAMED_OPT) and not any(arg.startswith('*')
+                                                                  for arg in args):
                     args.append('*')
                 if not annotation:
                     typename = self.get_str_type_of_node(arg_.initializer, True)


Test patch:
diff --git a/test-data/unit/stubgen.test b/test-data/unit/stubgen.test
--- a/test-data/unit/stubgen.test
+++ b/test-data/unit/stubgen.test
@@ -82,6 +82,19 @@ def f(x, **y): ...
 [out]
 def f(x, **y) -> None: ...
 
+[case testVarArgsWithKwVarArgs]
+def f(a, *b, **c): ...
+def g(a, *b, c=1): ...
+def h(a, *b, c=1, **d): ...
+def i(a, *, b=1): ...
+def j(a, *, b=1, **c): ...
+[out]
+def f(a, *b, **c) -> None: ...
+def g(a, *b, c: int = ...) -> None: ...
+def h(a, *b, c: int = ..., **d) -> None: ...
+def i(a, *, b: int = ...) -> None: ...
+def j(a, *, b: int = ..., **c) -> None: ...
+
 [case testClass]
 class A:
     def f(self, x):
Repository: python/mypy

Issue:
Allow 'x_' flags in the [mypy-foo] section of mypy.ini
This is a feature request.

I'd like to use the `[mypy-foo]` sections in `mypy.ini` to control behavior of some other tool (so I can have a centralized config file -- the tool is a linter that requires annotations if a certain flag is set). I can't reuse an existing mypy flag.

Currently mypy complains if it finds an unrecognized flag. That's still useful, but I'd like to exempt certain flags from those complaints. IIRC in mail headers, any flag starting with `X-` is allowed. I propose to do a similar thing for mypy -- if the flag name starts with `x_`, mypy will ignore it.


Discussion:

Resolving patch:
diff --git a/mypy/main.py b/mypy/main.py
--- a/mypy/main.py
+++ b/mypy/main.py
@@ -755,6 +755,8 @@ def parse_section(prefix: str, template: Options,
                         print("%s: Unrecognized report type: %s" % (prefix, orig_key),
                               file=sys.stderr)
                     continue
+                if key.startswith('x_'):
+                    continue  # Don't complain about `x_blah` flags
                 print("%s: Unrecognized option: %s = %s" % (prefix, key, section[orig_key]),
                       file=sys.stderr)
                 continue


Test patch:
diff --git a/test-data/unit/cmdline.test b/test-data/unit/cmdline.test
--- a/test-data/unit/cmdline.test
+++ b/test-data/unit/cmdline.test
@@ -441,6 +441,14 @@ ignore_missing_imports = True
 [out]
 main.py:2: error: Revealed type is 'Any'
 
+[case testConfigNoErrorForUnknownXFlagInSubsection]
+# cmd: mypy -c pass
+[file mypy.ini]
+[[mypy]
+[[mypy-foo]
+x_bad = 0
+[out]
+
 [case testDotInFilenameOKScript]
 # cmd: mypy a.b.py c.d.pyi
 [file a.b.py]