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

Issue:
pyinfo.py not compatible with Python 2
**Bug Report**

https://github.com/python/mypy/blob/master/mypy/pyinfo.py#L22
uses `sys.base_prefix`, but this does not exist in Python 2.

The code should check whether `base_prefix` exists, and if not return a copy of `prefix` instead.

**To Reproduce**

Use the options `--py2` and `--python-executable`.
Mypy will try to execute pyinfo.py using the given interpreter, which will fail.

**Actual Behavior**

```
Traceback (most recent call last):
  File "/opt/conda/lib/python3.9/runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/opt/conda/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/opt/conda/lib/python3.9/site-packages/mypy/__main__.py", line 34, in <module>
    console_entry()
  File "/opt/conda/lib/python3.9/site-packages/mypy/__main__.py", line 12, in console_entry
    main(None, sys.stdout, sys.stderr)
  File "mypy/main.py", line 96, in main
    svf.nsvf.init_handler,
  File "mypy/main.py", line 173, in run_build
  File "mypy/build.py", line 180, in build
  File "mypy/build.py", line 212, in _build
  File "mypy/modulefinder.py", line 782, in compute_search_paths
  File "mypy/modulefinder.py", line 624, in get_prefixes
    import getopt
  File "/opt/conda/lib/python3.9/subprocess.py", line 424, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/opt/conda/lib/python3.9/subprocess.py", line 528, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['.../python2', '/opt/conda/lib/python3.9/site-packages/mypy/pyinfo.py', 'getprefixes']' returned non-zero exit status 1.
```

Running the command manually gives
```
Traceback (most recent call last):
  File "/opt/conda/lib/python3.9/site-packages/mypy/pyinfo.py", line 43, in <module>
    print(repr(getprefixes()))
  File "/opt/conda/lib/python3.9/site-packages/mypy/pyinfo.py", line 22, in getprefixes
    return sys.base_prefix, sys.prefix
AttributeError: 'module' object has no attribute 'base_prefix'
```

**Your Environment**

- Mypy version used: 0.931
- Python version used: 2.7.5, 2.7.17


Discussion:
Thanks for the report, want to make a PR?
This stas says that less that 0.04% of downloads are for python2: https://pypistats.org/packages/mypy

<img width="937" alt="Снимок экрана 2022-02-23 в 5 17 44" src="https://user-images.githubusercontent.com/4660275/155251480-ead42643-9087-49b4-89c0-d6e1adee28ad.png">

However, I am not sure how accurate this number is.
That's not very informative because mypy does not run on Python 2 (and I believe it never has). It still supports type checking Python 2, but to do that you need to download it using 3.6+ first.

Resolving patch:
diff --git a/mypy/pyinfo.py b/mypy/pyinfo.py
--- a/mypy/pyinfo.py
+++ b/mypy/pyinfo.py
@@ -19,7 +19,7 @@
 
 def getprefixes():
     # type: () -> Tuple[str, str]
-    return sys.base_prefix, sys.prefix
+    return getattr(sys, "base_prefix", sys.prefix), sys.prefix
 
 
 def getsitepackages():


Test patch:
Repository: python/mypy

Issue:
Stubgen moves non default keyword-only argument in front of *
<!--
  If you're new to mypy and you're not sure whether what you're experiencing is a mypy bug, please see the "Question and Help" form
  instead.
-->

**Bug Report**

<!--
Note: If the problem you are reporting is about a specific library function, then the typeshed tracker is better suited
for this report: https://github.com/python/typeshed/issues
-->
Stubgen generates incorre stubs when a non default keyword-only argument is positioned after the asterix symbol in the signature.

**To Reproduce**

1. Create a function:

```python
def func(*, non_default_kwarg: bool, default_kwarg: bool = True):
    pass
```

2. Generate stubs

**Expected Behavior**

<!--
  How did you expect your project to behave?
  It’s fine if you’re not sure your understanding is correct.
  Write down what you thought would happen. If you just expected no errors, you can delete this section.
-->

```python
def func(*, non_default_kwarg: bool, default_kwarg: bool=...) -> Any: ...
```

**Actual Behavior**

<!--
  Did something go wrong?
  Is something broken, or not behaving as you expected?
-->

```python
def func(non_default_kwarg: bool, *, default_kwarg: bool=...) -> Any: ...
```

**Your Environment**

<!-- Include as many relevant details about the environment you experienced the bug in -->

- Mypy version used: 0.812

<!--
You can freely edit this text, please remove all the lines
you believe are unnecessary.
-->



Discussion:

Resolving patch:
diff --git a/mypy/stubgen.py b/mypy/stubgen.py
--- a/mypy/stubgen.py
+++ b/mypy/stubgen.py
@@ -649,9 +649,11 @@ def visit_func_def(self, o: FuncDef, is_abstract: bool = False,
                 # type "UnboundType" and will not match.
                 if not isinstance(get_proper_type(annotated_type), AnyType):
                     annotation = ": {}".format(self.print_annotation(annotated_type))
+
+            if kind.is_named() and not any(arg.startswith('*') for arg in args):
+                args.append('*')
+
             if arg_.initializer:
-                if kind.is_named() and not any(arg.startswith('*') for arg in args):
-                    args.append('*')
                 if not annotation:
                     typename = self.get_str_type_of_node(arg_.initializer, True, False)
                     if typename == '':


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
@@ -2580,3 +2580,8 @@ class A:
 def f(x: int, y: int) -> int: ...
 @t.overload
 def f(x: t.Tuple[int, int]) -> int: ...
+
+[case testNonDefaultKeywordOnlyArgAfterAsterisk]
+def func(*, non_default_kwarg: bool, default_kwarg: bool = True): ...
+[out]
+def func(*, non_default_kwarg: bool, default_kwarg: bool = ...): ...
Repository: python/mypy

Issue:
(🎁) `mypy -V` should print compiled status
A bunch of other tools show compiled status with version info, would be useful if mypy did too.
```
> black --version
black, 22.1.0 (compiled: yes)

> python -c "import pydantic.utils; print(pydantic.utils.version_info())":
             pydantic version: 1.9.0
            pydantic compiled: True
                 install path: /home/user/.local/lib/python3.10/site-packages/pydantic
               python version: 3.10.0 (default, Oct 11 2021, 05:33:59) [GCC 11.2.0]
                     platform: Linux-5.4.72-microsoft-standard-WSL2-x86_64-with-glibc2.34
     optional deps. installed: ['typing-extensions']


Discussion:
It does with `mypy -v`. Look for `LOG:  Compiled:               True`

Resolving patch:
diff --git a/mypy/main.py b/mypy/main.py
--- a/mypy/main.py
+++ b/mypy/main.py
@@ -492,9 +492,11 @@ def add_invertible_flag(flag: str,
     general_group.add_argument(
         '-v', '--verbose', action='count', dest='verbosity',
         help="More verbose messages")
+
+    compilation_status = "no" if __file__.endswith(".py") else "yes"
     general_group.add_argument(
         '-V', '--version', action=CapturableVersionAction,
-        version='%(prog)s ' + __version__,
+        version='%(prog)s ' + __version__ + f" (compiled: {compilation_status})",
         help="Show program's version number and exit",
         stdout=stdout)
 


Test patch:
Repository: python/mypy

Issue:
(🐞) Empty reveal locals should have a better output
```py
reveal_locals()
```
```
> mypy test.py
test.py:1:1: note: Revealed local types are:
Success: no issues found in 1 source file
```

This looks like a bug, I would expect something like:
```
> mypy test.py
test.py:1:1: note: There are no locals to reveal
Success: no issues found in 1 source file
```


Discussion:

Resolving patch:
diff --git a/mypy/messages.py b/mypy/messages.py
--- a/mypy/messages.py
+++ b/mypy/messages.py
@@ -1171,9 +1171,12 @@ def reveal_locals(self, type_map: Dict[str, Optional[Type]], context: Context) -
         # To ensure that the output is predictable on Python < 3.6,
         # use an ordered dictionary sorted by variable name
         sorted_locals = OrderedDict(sorted(type_map.items(), key=lambda t: t[0]))
-        self.note("Revealed local types are:", context)
-        for line in ['    {}: {}'.format(k, v) for k, v in sorted_locals.items()]:
-            self.note(line, context)
+        if sorted_locals:
+            self.note("Revealed local types are:", context)
+            for k, v in sorted_locals.items():
+                self.note('    {}: {}'.format(k, v), context)
+        else:
+            self.note("There are no locals to reveal", context)
 
     def unsupported_type_type(self, item: Type, context: Context) -> None:
         self.fail('Cannot instantiate type "Type[{}]"'.format(format_type_bare(item)), context)


Test patch:
Repository: python/mypy

Issue:
Explicit type aliases fail in typeshed
I can't reproduce this locally, but please have a look at the CI failures of python/typeshed#7534. The change is adding explicit type aliases to `_typeshed/*`. CI runs mypy 0.941 with all Python versions.

mypy fails for a simple `Any` type alias`
I can't reproduce this locally, but please have a look at the CI failures of python/typeshed#7535. The change is a simple type alias `Incomplete = Any`. The `TypeAlias` is optional, mypy fails with or without it. CI runs mypy 0.941 with all Python versions.


Discussion:
For reference #11305 added PEP 613 support.
#12134 (by @sobolevn) contains a fix for this bug. I think it might be good to excise that fix into a standalone PR.
I'll extract the `Any` fix from #12134 to a standalone PR. (cc @sobolevn)
Extracted the fix to #12429. The issue seems specific to typeshed (and possibly typeshed tests, in particular), and only reproduces for me if the files are passed to mypy in a specific order in the typeshed mypy test. I was able to reproduce it on macOS occasionally by randomizing the order of files passed to mypy.

Resolving patch:
diff --git a/mypy/build.py b/mypy/build.py
--- a/mypy/build.py
+++ b/mypy/build.py
@@ -2965,12 +2965,16 @@ def process_graph(graph: Graph, manager: BuildManager) -> None:
         # Order the SCC's nodes using a heuristic.
         # Note that ascc is a set, and scc is a list.
         scc = order_ascc(graph, ascc)
-        # If builtins is in the list, move it last.  (This is a bit of
-        # a hack, but it's necessary because the builtins module is
-        # part of a small cycle involving at least {builtins, abc,
-        # typing}.  Of these, builtins must be processed last or else
-        # some builtin objects will be incompletely processed.)
+        # Make the order of the SCC that includes 'builtins' and 'typing',
+        # among other things, predictable. Various things may  break if
+        # the order changes.
         if 'builtins' in ascc:
+            scc = sorted(scc, reverse=True)
+            # If builtins is in the list, move it last.  (This is a bit of
+            # a hack, but it's necessary because the builtins module is
+            # part of a small cycle involving at least {builtins, abc,
+            # typing}.  Of these, builtins must be processed last or else
+            # some builtin objects will be incompletely processed.)
             scc.remove('builtins')
             scc.append('builtins')
         if manager.options.verbosity >= 2:


Test patch:
Repository: python/mypy

Issue:
Let overload item have a wider return type than implementation
A wider return type can be useful if a decorator gets a more precise error type as part of a typeshed update.

@wrobell reported this concrete example in https://github.com/python/mypy/issues/12021#issuecomment-1065542606:

```py
import typing as tp
from contextlib import asynccontextmanager

T = tp.TypeVar('T')

@tp.overload
def f() -> tp.AsyncContextManager[int]:
    ...

@tp.overload
def f(cls: type[T]) -> tp.AsyncContextManager[T]:
    ...

@asynccontextmanager
async def f(cls=int):
    yield 1
```

Mypy 0.940 got a more precise type for `@asynccontextmanager`, and this resulted in apparent false positives:
```
tp.py:14: error: Overloaded function implementation cannot produce return type of signature 1
tp.py:14: error: Overloaded function implementation cannot produce return type of signature 2
```

I think that we can allow an overload item to have a more general return type than the implementation, for convenience.


Discussion:

Resolving patch:
diff --git a/mypy/checker.py b/mypy/checker.py
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -600,7 +600,8 @@ def check_overlapping_overloads(self, defn: OverloadedFuncDef) -> None:
                     self.msg.overloaded_signatures_arg_specific(i + 1, defn.impl)
 
                 # Is the overload alternative's return type a subtype of the implementation's?
-                if not is_subtype_no_promote(sig1.ret_type, impl.ret_type):
+                if not (is_subtype_no_promote(sig1.ret_type, impl.ret_type) or
+                        is_subtype_no_promote(impl.ret_type, sig1.ret_type)):
                     self.msg.overloaded_signatures_ret_specific(i + 1, defn.impl)
 
     # Here's the scoop about generators and coroutines.


Test patch:
diff --git a/test-data/unit/check-overloading.test b/test-data/unit/check-overloading.test
--- a/test-data/unit/check-overloading.test
+++ b/test-data/unit/check-overloading.test
@@ -6328,3 +6328,24 @@ if True:
 def f2(x): ...
 if True:
     def f2(x): ...  # E: Name "f2" already defined on line 17
+
+[case testOverloadItemHasMoreGeneralReturnType]
+from typing import overload
+
+@overload
+def f() -> object: ...
+
+@overload
+def f(x: int) -> object: ...
+
+def f(x: int = 0) -> int:
+    return x
+
+@overload
+def g() -> object: ...
+
+@overload
+def g(x: int) -> str: ...
+
+def g(x: int = 0) -> int:  # E: Overloaded function implementation cannot produce return type of signature 2
+    return x
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
@@ -2084,6 +2084,7 @@ a.py:5: error: "list" expects 1 type argument, but 2 given
 ==
 
 [case testPreviousErrorInOverloadedFunction]
+# flags: --strict-optional
 import a
 [file a.py]
 from typing import overload
Repository: python/mypy

Issue:
Stubgen applies Generator type to function with nested generator
**Bug Report**

When stubgen encounters a function with a nested generator-function, that generator type is used for the return type of the function, even if the function itself does not return a generator.

**To Reproduce**

1. Create a file `generator.py`:
   ```py
   def some_function():
       def generator():
           yield "a"

       return 5
   ```
2. Run `stubgen generator.py`.

**Expected Behavior**
The function in the generated type stub has a "regular" return type.
```py
from collections.abc import Generator
from typing import Any

def some_function() -> Any: ...  # or int
```

**Actual Behavior**
The stub function has a `Generator[None, None, Any]` type.
```py
from collections.abc import Generator
from typing import Any

def some_function() -> Generator[None, None, Any]: ...
```

**Your Environment**

- Mypy version used: 0.930
- Mypy command-line flags: `stubgen generator.py`
- Mypy configuration options from `mypy.ini` (and other config files): -
- Python version used: 3.9.9
- Operating system and version: macOS 12.1




Discussion:

Resolving patch:
diff --git a/mypy/traverser.py b/mypy/traverser.py
--- a/mypy/traverser.py
+++ b/mypy/traverser.py
@@ -368,8 +368,20 @@ def has_return_statement(fdef: FuncBase) -> bool:
     return seeker.found
 
 
-class YieldSeeker(TraverserVisitor):
+class FuncCollectorBase(TraverserVisitor):
+    def __init__(self) -> None:
+        self.inside_func = False
+
+    def visit_func_def(self, defn: FuncDef) -> None:
+        if not self.inside_func:
+            self.inside_func = True
+            super().visit_func_def(defn)
+            self.inside_func = False
+
+
+class YieldSeeker(FuncCollectorBase):
     def __init__(self) -> None:
+        super().__init__()
         self.found = False
 
     def visit_yield_expr(self, o: YieldExpr) -> None:
@@ -382,17 +394,6 @@ def has_yield_expression(fdef: FuncBase) -> bool:
     return seeker.found
 
 
-class FuncCollectorBase(TraverserVisitor):
-    def __init__(self) -> None:
-        self.inside_func = False
-
-    def visit_func_def(self, defn: FuncDef) -> None:
-        if not self.inside_func:
-            self.inside_func = True
-            super().visit_func_def(defn)
-            self.inside_func = False
-
-
 class ReturnCollector(FuncCollectorBase):
     def __init__(self) -> None:
         super().__init__()


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
@@ -2619,3 +2619,12 @@ class PT(Protocol[T, T2]):
 def func(*, non_default_kwarg: bool, default_kwarg: bool = True): ...
 [out]
 def func(*, non_default_kwarg: bool, default_kwarg: bool = ...): ...
+
+[case testNestedGenerator]
+def f():
+    def g():
+        yield 0
+
+    return 0
+[out]
+def f(): ...
Repository: python/mypy

Issue:
"variable arguments" in error message
Checking `sum(*1)` produces "error: List or tuple expected as variable arguments". I'm pretty sure this should say *variadic* arguments.


Discussion:
Hi there! Is this issue still open?

Resolving patch:
diff --git a/mypy/messages.py b/mypy/messages.py
--- a/mypy/messages.py
+++ b/mypy/messages.py
@@ -944,7 +944,7 @@ def could_not_infer_type_arguments(self, callee_type: CallableType, n: int,
             self.fail('Cannot infer function type argument', context)
 
     def invalid_var_arg(self, typ: Type, context: Context) -> None:
-        self.fail('List or tuple expected as variable arguments', context)
+        self.fail('List or tuple expected as variadic arguments', context)
 
     def invalid_keyword_var_arg(self, typ: Type, is_mapping: bool, context: Context) -> None:
         typ = get_proper_type(typ)


Test patch:
diff --git a/test-data/unit/check-varargs.test b/test-data/unit/check-varargs.test
--- a/test-data/unit/check-varargs.test
+++ b/test-data/unit/check-varargs.test
@@ -275,7 +275,7 @@ class CC(C): pass
 a = None # type: A
 
 f(*None)
-f(*a)    # E: List or tuple expected as variable arguments
+f(*a)    # E: List or tuple expected as variadic arguments
 f(*(a,))
 
 def f(a: 'A') -> None:
@@ -544,9 +544,9 @@ if int():
 if int():
     b, b = f(b, b, *aa) # E: Argument 3 to "f" has incompatible type "*List[A]"; expected "B"
 if int():
-    a, b = f(a, *a)  # E: List or tuple expected as variable arguments
+    a, b = f(a, *a)  # E: List or tuple expected as variadic arguments
 if int():
-    a, b = f(*a)     # E: List or tuple expected as variable arguments
+    a, b = f(*a)     # E: List or tuple expected as variadic arguments
 
 if int():
     a, a = f(*aa)
@@ -758,5 +758,5 @@ bar(*good1)
 bar(*good2)
 bar(*good3)
 bar(*bad1)  # E: Argument 1 to "bar" has incompatible type "*I[str]"; expected "float"
-bar(*bad2)  # E: List or tuple expected as variable arguments
+bar(*bad2)  # E: List or tuple expected as variadic arguments
 [builtins fixtures/dict.pyi]
Repository: python/mypy

Issue:
stubtest false positive for `...` in param default
From `python -m mypy.stubtest --custom-typeshed-dir . wsgiref`:

```
error: wsgiref.types._Readable.read is inconsistent, runtime argument "size" has a default value of type builtins.ellipsis, which is incompatible with stub argument type builtins.int
Stub: at line 28
def (self: wsgiref.types._Readable, builtins.int =) -> builtins.bytes
Runtime: at line 47 in file /Users/jelle/py/cpython/Lib/wsgiref/types.py
def (self, size: int = Ellipsis, /) -> bytes
```

The stub and implementation are exactly the same.

Probably stubtest should handle runtime Protocols more smartly.


Discussion:

Resolving patch:
diff --git a/mypy/stubtest.py b/mypy/stubtest.py
--- a/mypy/stubtest.py
+++ b/mypy/stubtest.py
@@ -419,6 +419,8 @@ def _verify_arg_default_value(
                 and stub_type is not None
                 # Avoid false positives for marker objects
                 and type(runtime_arg.default) != object
+                # And ellipsis
+                and runtime_arg.default is not ...
                 and not is_subtype_helper(runtime_type, stub_type)
             ):
                 yield (


Test patch:
diff --git a/mypy/test/teststubtest.py b/mypy/test/teststubtest.py
--- a/mypy/test/teststubtest.py
+++ b/mypy/test/teststubtest.py
@@ -43,6 +43,7 @@ def __getitem__(self, typeargs: Any) -> object: ...
 
 Callable: _SpecialForm = ...
 Generic: _SpecialForm = ...
+Protocol: _SpecialForm = ...
 
 class TypeVar:
     def __init__(self, name, covariant: bool = ..., contravariant: bool = ...) -> None: ...
@@ -1020,6 +1021,27 @@ class _Options(TypedDict):
             error="opt3",
         )
 
+    @collect_cases
+    def test_protocol(self) -> Iterator[Case]:
+        if sys.version_info < (3, 7):
+            return
+        yield Case(
+            stub="""
+            from typing_extensions import Protocol
+
+            class X(Protocol):
+                def foo(self, x: int, y: bytes = ...) -> str: ...
+            """,
+            runtime="""
+            from typing_extensions import Protocol
+
+            class X(Protocol):
+                def foo(self, x: int, y: bytes = ...) -> str: ...
+            """,
+            # TODO: this should not be an error, #12820
+            error="X.__init__"
+        )
+
 
 def remove_color_code(s: str) -> str:
     return re.sub("\\x1b.*?m", "", s)  # this works!