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

Issue:
Empty argument list of a Callable is translated to <TypeList> in stub file
[PEP 484](https://www.python.org/dev/peps/pep-0484/#callable) mentions an example for typing a function with no arguments (I added sample function body to be able to pass it to ``stubgen``):

```python
from typing import Callable

def feeder(get_next_item: Callable[[], str]) -> None:
    return None
```
Now run ``stubgen`` over the file with the above code:

```sh
$ python -m mypy.stubgen spam
Created out/spam.pyi
```
The following stub file is generated:
```python
# Stubs for spam (Python 3.6)
#
# NOTE: This dynamically typed stub was automatically generated by stubgen.

from typing import Callable

def feeder(get_next_item: Callable[<TypeList >, str]) -> None: ...
```
What confuses me is the ``<TypeList >`` instead of an empty list.


Discussion:
Probably a simple bug in stubgen, hopefully you can fix it yourself and submit a PR.
As noted in #4640, this issue occurs with all TypeLists in Callables, not just empty ones.

Resolving patch:
diff --git a/mypy/stubgen.py b/mypy/stubgen.py
--- a/mypy/stubgen.py
+++ b/mypy/stubgen.py
@@ -65,7 +65,10 @@
 from mypy.stubgenc import parse_all_signatures, find_unique_signatures, generate_stub_for_c_module
 from mypy.stubutil import is_c_module, write_header
 from mypy.options import Options as MypyOptions
-from mypy.types import Type, TypeStrVisitor, AnyType, CallableType, UnboundType, NoneTyp, TupleType
+from mypy.types import (
+    Type, TypeStrVisitor, AnyType, CallableType,
+    UnboundType, NoneTyp, TupleType, TypeList,
+)
 from mypy.visitor import NodeVisitor
 
 Options = NamedTuple('Options', [('pyversion', Tuple[int, int]),
@@ -252,6 +255,9 @@ def visit_unbound_type(self, t: UnboundType)-> str:
     def visit_none_type(self, t: NoneTyp) -> str:
         return "None"
 
+    def visit_type_list(self, t: TypeList) -> str:
+        return '[{}]'.format(self.list_str(t.items))
+
 
 class AliasPrinter(NodeVisitor[str]):
 


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
@@ -886,3 +886,12 @@ def g(): ...
 def f(): ...
 [out]
 def f() -> None: ...
+
+[case testCallable]
+from typing import Callable
+
+x: Callable[[int, int], int]
+[out]
+from typing import Callable
+
+x: Callable[[int, int], int]
Repository: python/mypy

Issue:
[Enhancement] No strict option for setup.cfg
I tried to use strict mode from a configuration file:
setup.cfg:
```
[mypy]
strict=True
```
Then mypy says that the option is not recognized. It would be nice to be able to enable strict mode from the setup.cfg


Discussion:
I don't know of a conscious decision to leave this option out. It appears it is also not available in `mypy.ini` as well. It should be pretty easy to fix in our option parsing.
It was a conscious decision -- nothing in mypy checks for 'options.strict',
instead --strict just turns on a bunch of other flags, and the logic to do
this correctly from the config file was too convoluted to do. Nevertheless
we might be able to do this, but since it's really just a shorthand, I
recommend being explicit in your config file.

I found this issue after being confused by the "Unrecognized option: strict" message.

The reasoning for not supporting it makes sense: maybe it's worth making MyPy show a message explaining that this is intentional and what to do instead, rather than just giving the uninformative "Unrecognized option" message?

Current message:
```
mypy.ini: [mypy]: Unrecognized option: strict = True
```

Straw suggestion:

```
mypy.ini: [mypy]: strict = True is not supported here: specify individual options instead
```
Improving the error message is a good idea.

Resolving patch:
diff --git a/mypy/main.py b/mypy/main.py
--- a/mypy/main.py
+++ b/mypy/main.py
@@ -766,8 +766,13 @@ def parse_section(prefix: str, template: Options,
                     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)
+                elif key == 'strict':
+                    print("%s: Strict mode is not supported in configuration files: specify "
+                          "individual flags instead (see 'mypy -h' for the list of flags enabled "
+                          "in strict mode)" % prefix, file=sys.stderr)
+                else:
+                    print("%s: Unrecognized option: %s = %s" % (prefix, key, section[orig_key]),
+                          file=sys.stderr)
                 continue
             ct = type(dv)
         v = None  # type: Any


Test patch:
Repository: python/mypy

Issue:
Python 3.5.0 is not supported to run mypy
While in general we support running mypy with Python 3.4 and higher, 3.5.0 specifically is not supported (we just found this out rather painfully). This is because the 3.5.0 stdlib has a very old version of typing.py that does not support all the features mypy uses. Higher versions of Python 3.6 (i.e. 3.5.1 and up) work fine. 3.4.x works too because there typing.py is taken from PyPI.

We should probably document this and/or check for it when mypy starts. Currently the only runtime version check I can find is in setup.py, and I'm not convinced that it always triggers (setup.py isn't run when installing via wheels).

Note that our Travis-CI setup explicitly tests with Python 3.5.1 -- this keeps us honest (while I'm not 100% sure 3.6.0 works, at least its typing.py is newer than the one from 3.5.1, so I expect it's fine).


Discussion:

Resolving patch:
diff --git a/mypy/main.py b/mypy/main.py
--- a/mypy/main.py
+++ b/mypy/main.py
@@ -51,6 +51,14 @@ def main(script_path: Optional[str], args: Optional[List[str]] = None) -> None:
         args: Custom command-line arguments.  If not given, sys.argv[1:] will
         be used.
     """
+    # Check for known bad Python versions.
+    if sys.version_info[:2] < (3, 4):
+        sys.exit("Running mypy with Python 3.3 or lower is not supported; "
+                 "please upgrade to 3.4 or newer")
+    if sys.version_info[:3] == (3, 5, 0):
+        sys.exit("Running mypy with Python 3.5.0 is not supported; "
+                 "please upgrade to 3.5.1 or newer")
+
     t0 = time.time()
     # To log stat() calls: os.stat = stat_proxy
     if script_path:


Test patch:
Repository: python/mypy

Issue:
Fine-grained: Nested class causes hang
This fine-grained incremental mode test case hangs:

```
[case testRefreshNestedClassWithSelfReference]
import a
[file a.py]
import b

def f(self) -> None:
    b.y
    class C:
        z: C
[file b.py]
y = 0
[file b.py.2]
y = ''
[out]
==
```


Discussion:

Resolving patch:
diff --git a/mypy/semanal.py b/mypy/semanal.py
--- a/mypy/semanal.py
+++ b/mypy/semanal.py
@@ -1066,8 +1066,15 @@ def setup_class_def_analysis(self, defn: ClassDef) -> None:
             if kind == LDEF:
                 # We need to preserve local classes, let's store them
                 # in globals under mangled unique names
-                local_name = defn.info._fullname + '@' + str(defn.line)
-                defn.info._fullname = self.cur_mod_id + '.' + local_name
+                #
+                # TODO: Putting local classes into globals breaks assumptions in fine-grained
+                #     incremental mode and we should avoid it.
+                if '@' not in defn.info._fullname:
+                    local_name = defn.info._fullname + '@' + str(defn.line)
+                    defn.info._fullname = self.cur_mod_id + '.' + local_name
+                else:
+                    # Preserve name from previous fine-grained incremental run.
+                    local_name = defn.info._fullname
                 defn.fullname = defn.info._fullname
                 self.globals[local_name] = node
 


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
@@ -2832,3 +2832,22 @@ class C(Enum):
 ==
 a.py:4: error: Argument 1 to "f" has incompatible type "C"; expected "int"
 a.py:5: error: Argument 1 to "f" has incompatible type "C"; expected "int"
+
+[case testRefreshNestedClassWithSelfReference]
+import a
+[file a.py]
+import b
+
+def f(self) -> None:
+    b.y
+    class C:
+        z: C
+[file b.py]
+y = 0
+[file b.py.2]
+y = ''
+[file b.py.3]
+y = 0
+[out]
+==
+==
Repository: python/mypy

Issue:
__ne__ doesn't allow returning NotImplemented
It seems that mypy doesn't allow `__ne__` returning `NotImplemented`, (this is allowed with `__eq__`).
And when I try explicitly adding `NotImplemented` as a possible return type, I get a run-time error:
```
  File ".../pod.py", line 65, in PlainOldData
    def __ne__(self, other: Any) -> Union[bool, NotImplemented]:
  File "/usr/lib/python3.6/typing.py", line 682, in inner
    return func(*args, **kwds)
  File "/usr/lib/python3.6/typing.py", line 800, in __getitem__
    parameters = tuple(_type_check(p, msg) for p in parameters)
  File "/usr/lib/python3.6/typing.py", line 800, in <genexpr>
    parameters = tuple(_type_check(p, msg) for p in parameters)
  File "/usr/lib/python3.6/typing.py", line 374, in _type_check
    raise TypeError(msg + " Got %.100r." % (arg,))
TypeError: Union[arg, ...]: each arg must be a type. Got NotImplemented.
```

If I change this to `def __ne__(self, other: Any) -> Union[bool, type(NotImplemented)]:`, then mypy complains: 
```
error: invalid type comment or annotation
note: Suggestion: use type[...] instead of type(...)
```

and when I try using this suggestion, I get a runtime error:
```
TypeError: 'type' object is not subscriptable
```

@gvanrossum  suggested (in [issue 1101](https://github.com/python/mypy/issues/1101#issuecomment-374685779)) that this was due to `__ne__` not being in `sharedparse.__MAGICMETHODS`; but it does appear to be there.



Discussion:
But it's not in `BINARY_MAGIC_METHODS`.
Oops. I'll put together a PR.

Resolving patch:
diff --git a/mypy/sharedparse.py b/mypy/sharedparse.py
--- a/mypy/sharedparse.py
+++ b/mypy/sharedparse.py
@@ -118,6 +118,7 @@
     "__lt__",
     "__mod__",
     "__mul__",
+    "__ne__",
     "__or__",
     "__pow__",
     "__radd__",


Test patch:
Repository: python/mypy

Issue:
warn-unused-ignores does not respect follow-imports=silent
```
$ cat imported.py
a: int = 'foo'

b: int = 3  # type: ignore

$ cat main.py 
import imported

$ mypy --warn-unused-ignores --follow-imports=silent main.py
imported.py:3: note: unused 'type: ignore' comment
```

`follow-imports=silent` correctly silences the type error on line 1 of `imported.py`, but fails to silence the "unused type: ignore comment" note.


Discussion:
Confirmed on master. Thank you for the small and simple repro!

Resolving patch:
diff --git a/mypy/errors.py b/mypy/errors.py
--- a/mypy/errors.py
+++ b/mypy/errors.py
@@ -294,7 +294,7 @@ def clear_errors_in_targets(self, path: str, targets: Set[str]) -> None:
 
     def generate_unused_ignore_notes(self, file: str) -> None:
         ignored_lines = self.ignored_lines[file]
-        if not self.is_typeshed_file(file):
+        if not self.is_typeshed_file(file) and file not in self.ignored_files:
             for line in ignored_lines - self.used_ignored_lines[file]:
                 # Don't use report since add_error_info will ignore the error!
                 info = ErrorInfo(self.import_context(), file, self.current_module(), None,


Test patch:
diff --git a/test-data/unit/check-flags.test b/test-data/unit/check-flags.test
--- a/test-data/unit/check-flags.test
+++ b/test-data/unit/check-flags.test
@@ -372,6 +372,12 @@ x + ""  # E: Unsupported operand types for + ("int" and "str")
 1 + ""
 x = 0
 
+[case testFollowImportsSilentTypeIgnore]
+# flags: --warn-unused-ignores --follow-imports=silent
+import mod
+[file mod.py]
+x = 3  # type: ignore
+
 [case testFollowImportsSkip]
 # flags: --follow-imports=skip
 from mod import x
Repository: python/mypy

Issue:
User-specific config file
Feature request. According to my search-fu, it hasn't been discussed yet.

`mypy` with no `--config-file` specified will check for `mypy.ini` first, use to `setup.cfg` otherwise, and ultimately fallback to the built-in defaults if none of them are present. I would like to have a user-default config that would be used instead. Would it be too crazy to check for `~/.mypy.ini` before falling back to the built-in defaults?

I would find this useful for quick prototyping without having to copy&paste my preferred configuration from other projects. It's also quite a common pattern in other static analysis tools like linters.


Discussion:
This looks like a simple project which you can probably do yourself in a
few lines -- just submit a PR.

Sure! Happy to tackle it.

Resolving patch:
diff --git a/mypy/defaults.py b/mypy/defaults.py
--- a/mypy/defaults.py
+++ b/mypy/defaults.py
@@ -3,3 +3,6 @@
 PYTHON3_VERSION_MIN = (3, 3)
 CACHE_DIR = '.mypy_cache'
 CONFIG_FILE = 'mypy.ini'
+SHARED_CONFIG_FILES = ('setup.cfg',)
+USER_CONFIG_FILES = ('~/.mypy.ini',)
+CONFIG_FILES = (CONFIG_FILE,) + SHARED_CONFIG_FILES + USER_CONFIG_FILES
diff --git a/mypy/main.py b/mypy/main.py
--- a/mypy/main.py
+++ b/mypy/main.py
@@ -444,7 +444,7 @@ def add_invertible_flag(flag: str,
                         help="Script x becomes module x instead of __main__")
     parser.add_argument('--config-file',
                         help="Configuration file, must have a [mypy] section "
-                        "(defaults to {})".format(defaults.CONFIG_FILE))
+                        "(defaults to {})".format(', '.join(defaults.CONFIG_FILES)))
     add_invertible_flag('--show-column-numbers', default=False,
                         help="Show column numbers in error messages")
     parser.add_argument('--find-occurrences', metavar='CLASS.MEMBER',
@@ -677,21 +677,18 @@ def add_invertible_flag(flag: str,
     'always_false': lambda s: [p.strip() for p in s.split(',')],
 }
 
-SHARED_CONFIG_FILES = ('setup.cfg',)
-
 
 def parse_config_file(options: Options, filename: Optional[str]) -> None:
     """Parse a config file into an Options object.
 
     Errors are written to stderr but are not fatal.
 
-    If filename is None, fall back to default config file and then
-    to setup.cfg.
+    If filename is None, fall back to default config files.
     """
     if filename is not None:
         config_files = (filename,)  # type: Tuple[str, ...]
     else:
-        config_files = (defaults.CONFIG_FILE,) + SHARED_CONFIG_FILES
+        config_files = tuple(map(os.path.expanduser, defaults.CONFIG_FILES))
 
     parser = configparser.RawConfigParser()
 
@@ -710,7 +707,7 @@ def parse_config_file(options: Options, filename: Optional[str]) -> None:
         return
 
     if 'mypy' not in parser:
-        if filename or file_read not in SHARED_CONFIG_FILES:
+        if filename or file_read not in defaults.SHARED_CONFIG_FILES:
             print("%s: No [mypy] section in config file" % file_read, file=sys.stderr)
     else:
         section = parser['mypy']


Test patch:
Repository: python/mypy

Issue:
IntEnum "is not indexable"
```
from enum import IntEnum
Color = IntEnum('Color', 'red green blue')
Color['green']
```
...yields:
```
test.py:3: error: Value of type "Type[Color]" is not indexable
```

This example is more or less [straight out of the enum docs](http://cpython-test-docs.readthedocs.io/en/latest/library/enum.html#programmatic-access-to-enumeration-members-and-their-attributes) -- my expectation is that it should not be a type error.

Mypy version 025e3decfaa95f42c721c4662cdf2dd748db06a3 


Discussion:
Note that this problem is absent for a simple `Enum`. Also `IntEnum` fails the following code:
```python
for c in Color:  # E: not iterable
    reveal_type(c)
```
I thought this should be fixed by https://github.com/python/mypy/pull/4319 @elazarg what do you think?

It only happens for functional api of non-`Enum` enums. I will look into it.

Resolving patch:
diff --git a/mypy/semanal_enum.py b/mypy/semanal_enum.py
--- a/mypy/semanal_enum.py
+++ b/mypy/semanal_enum.py
@@ -80,6 +80,7 @@ def build_enum_call_typeinfo(self, name: str, items: List[str], fullname: str) -
         base = self.api.named_type_or_none(fullname)
         assert base is not None
         info = self.api.basic_new_typeinfo(name, base)
+        info.metaclass_type = info.calculate_metaclass_type()
         info.is_enum = True
         for item in items:
             var = Var(item)


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
@@ -392,6 +392,16 @@ x = y
 [out]
 main:8: error: Incompatible types in assignment (expression has type "__main__.B.E", variable has type "__main__.A.E")
 
+[case testFunctionalEnumProtocols]
+from enum import IntEnum
+Color = IntEnum('Color', 'red green blue')
+reveal_type(Color['green'])  # E: Revealed type is '__main__.Color'
+for c in Color:
+    reveal_type(c)  # E: Revealed type is '__main__.Color*'
+reveal_type(list(Color))  # E: Revealed type is 'builtins.list[__main__.Color*]'
+
+[builtins fixtures/list.pyi]
+
 [case testEnumWorkWithForward]
 from enum import Enum
 a: E = E.x
Repository: python/mypy

Issue:
attrs plugin: incorrect handling of attr.ib(default=42, init=False)
If `attr.ib()` has init=False and a default value, it should be possible to add more non-default attributes. However, currently this breaks:

```python
import attr

@attr.s
class C:
   x = attr.ib(init=False, default=42)
   y = attr.ib()
```

with `error: Non-default attributes not allowed after default attributes.`.

ref python-attrs/attrs#389


Discussion:

Resolving patch:
diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py
--- a/mypy/plugins/attrs.py
+++ b/mypy/plugins/attrs.py
@@ -240,11 +240,12 @@ def _analyze_class(ctx: 'mypy.plugin.ClassDefContext', auto_attribs: bool) -> Li
     # attributes for all classes have been read, because subclasses can override parents.
     last_default = False
     for attribute in attributes:
-        if attribute.init and not attribute.has_default and last_default:
-            ctx.api.fail(
-                "Non-default attributes not allowed after default attributes.",
-                attribute.context)
-        last_default = attribute.has_default
+        if attribute.init:
+            if not attribute.has_default and last_default:
+                ctx.api.fail(
+                    "Non-default attributes not allowed after default attributes.",
+                    attribute.context)
+            last_default |= attribute.has_default
 
     return attributes
 


Test patch:
diff --git a/test-data/unit/check-attr.test b/test-data/unit/check-attr.test
--- a/test-data/unit/check-attr.test
+++ b/test-data/unit/check-attr.test
@@ -844,3 +844,16 @@ class A:
     x: int = attr.ib(factory=list)  # E: Incompatible types in assignment (expression has type "List[T]", variable has type "int")
     y: str = attr.ib(factory=my_factory) # E: Incompatible types in assignment (expression has type "int", variable has type "str")
 [builtins fixtures/list.pyi]
+
+[case testAttrsDefaultAndInit]
+import attr
+
+@attr.s
+class C:
+   a = attr.ib(init=False, default=42)
+   b = attr.ib()  # Ok because previous attribute is init=False
+   c = attr.ib(default=44)
+   d = attr.ib(init=False)  # Ok because this attribute is init=False
+   e = attr.ib()  # E: Non-default attributes not allowed after default attributes.
+
+[builtins fixtures/bool.pyi]
Repository: python/mypy

Issue:
dunder parameter: Unexpected Keyword Argument
Consider the following:

```python
def func(*, __param__=False):
    return __param__

assert func(__param__=True) is True
```

mypy complains: `"error: Unexpected keyword argument for "__param__" for "func"`. This can be experienced directly by looking at `inspect.Signature` and supplying the an argument for the keyword-only parameter `__validate_parameters__`.

This appears(?) to be related to a mis-implementation of the following: https://github.com/python/typing/issues/336


Discussion:
I'm not sure this is a misimplementation: it's behaving exactly as described in the linked issue.

To accommodate the inspect.Signature use case, perhaps we can *not* treat the param as positional-only if its name also ends with `__`, or if it is already keyword-only.
Either the PEP revision was accepted without enough consideration, or the implementation of ``inspect.Signature`` is non-compliant.

You are correct that it follows the letter of the implementation of python/typing#336. I either misunderstand the spirit of that revision – Python distinguishes between a leading and a surrounding `__` – or (I'd suggest) the revision is an anti-pattern.
 Special casing names ending with `__` sounds reasonable to me. Being able to declare positional-only arguments is a useful feature, but there should be no reason to also have a `__` suffix for positional-only arguments.
This was an oversight in the spec! We meant to use the same naming convention as Python uses for `__private` names, from which `__dunder__` names are explicitly excluded. If you could submit a PR for mypy and another for PEP 484 I'd be happe to review them.

Resolving patch:
diff --git a/mypy/sharedparse.py b/mypy/sharedparse.py
--- a/mypy/sharedparse.py
+++ b/mypy/sharedparse.py
@@ -104,4 +104,4 @@ def special_function_elide_names(name: str) -> bool:
 
 
 def argument_elide_name(name: Optional[str]) -> bool:
-    return name is not None and name.startswith("__")
+    return name is not None and name.startswith("__") and not name.endswith("__")


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
@@ -2073,25 +2073,18 @@ h(7) # E: Cannot call function of unknown type
 
 [case testPositionalOnlyArg]
 def f(__a: int) -> None: pass
+def g(__a__: int) -> None: pass
 
 f(1)
 f(__a=1) # E: Unexpected keyword argument "__a" for "f"
 
-[builtins fixtures/bool.pyi]
-[out]
-main:1: note: "f" defined here
-
-[case testPositionalOnlyArgFastparse]
-
-
-def f(__a: int) -> None: pass
-
-f(1)
-f(__a=1) # E: Unexpected keyword argument "__a" for "f"
+g(1)
+# Argument names that also end with __ are not positional-only.
+g(__a__=1)
 
 [builtins fixtures/bool.pyi]
 [out]
-main:3: note: "f" defined here
+main:1: note: "f" defined here
 
 [case testMagicMethodPositionalOnlyArg]
 class A(object):