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

Issue:
Support unreachable blocks in partially defined check
For the partially defined check (`--enable-error-code partially-defined`), mypy should detect unreachable blocks:

Assuming we're running python3.6 in the following block:
```python
if sys.version_info >= (3, 6):
    x = 1
print(x)  # This should not generate an error but currently does.
```


Discussion:

Resolving patch:
diff --git a/mypy/partially_defined.py b/mypy/partially_defined.py
--- a/mypy/partially_defined.py
+++ b/mypy/partially_defined.py
@@ -203,9 +203,13 @@ def visit_if_stmt(self, o: IfStmt) -> None:
             e.accept(self)
         self.tracker.start_branch_statement()
         for b in o.body:
+            if b.is_unreachable:
+                continue
             b.accept(self)
             self.tracker.next_branch()
         if o.else_body:
+            if o.else_body.is_unreachable:
+                self.tracker.skip_branch()
             o.else_body.accept(self)
         self.tracker.end_branch_statement()
 
@@ -218,7 +222,10 @@ def visit_match_stmt(self, o: MatchStmt) -> None:
             guard = o.guards[i]
             if guard is not None:
                 guard.accept(self)
-            o.bodies[i].accept(self)
+            if not o.bodies[i].is_unreachable:
+                o.bodies[i].accept(self)
+            else:
+                self.tracker.skip_branch()
             is_catchall = infer_pattern_value(pattern) == ALWAYS_TRUE
             if not is_catchall:
                 self.tracker.next_branch()


Test patch:
diff --git a/test-data/unit/check-partially-defined.test b/test-data/unit/check-partially-defined.test
--- a/test-data/unit/check-partially-defined.test
+++ b/test-data/unit/check-partially-defined.test
@@ -367,3 +367,22 @@ def f() -> None:
     d = a
     d = b
 [builtins fixtures/tuple.pyi]
+
+[case testUnreachable]
+# flags: --enable-error-code partially-defined
+import typing
+
+if typing.TYPE_CHECKING:
+    x = 1
+elif int():
+    y = 1
+else:
+    y = 2
+a = x
+
+if not typing.TYPE_CHECKING:
+    pass
+else:
+    z = 1
+a = z
+[typing fixtures/typing-medium.pyi]
diff --git a/test-data/unit/check-python310.test b/test-data/unit/check-python310.test
--- a/test-data/unit/check-python310.test
+++ b/test-data/unit/check-python310.test
@@ -1789,6 +1789,30 @@ def f6(a: object) -> None:
             pass
 [builtins fixtures/tuple.pyi]
 
+[case testPartiallyDefinedMatchUnreachable]
+# flags: --enable-error-code partially-defined
+import typing
+
+def f0(x: int) -> int:
+    match x:
+        case 1 if not typing.TYPE_CHECKING:
+            pass
+        case 2:
+            y = 2
+        case _:
+            y = 3
+    return y # No error.
+
+def f1(x: int) -> int:
+    match x:
+        case 1 if not typing.TYPE_CHECKING:
+            pass
+        case 2:
+            y = 2
+    return y  # E: Name "y" may be undefined
+
+[typing fixtures/typing-medium.pyi]
+
 [case testTypeAliasWithNewUnionSyntaxAndNoneLeftOperand]
 from typing import overload
 class C:
Repository: python/mypy

Issue:
Provide a way to run mypy and mypyc tests inside a Docker container
My primary motivation is that mypyc "run" tests tend to be very slow on macOS. Using a Docker container would make them much faster.

This can also help if it's difficult to get a test to pass for some reason locally. Docker provides a repeatable, isolated environment.


Discussion:

Resolving patch:
diff --git a/misc/docker/build.py b/misc/docker/build.py
new file mode 100644
--- /dev/null
+++ b/misc/docker/build.py
@@ -0,0 +1,46 @@
+"""Build a "mypy-test" Linux Docker container for running mypy/mypyc tests.
+
+This allows running Linux tests under a non-Linux operating system. Mypyc
+tests can also run much faster under Linux that the host OS.
+
+NOTE: You may need to run this as root (using sudo).
+
+Run with "--no-cache" to force reinstallation of mypy dependencies.
+Run with "--pull" to force update of the Linux (Ubuntu) base image.
+
+After you've built the container, use "run.sh" to run tests. Example:
+
+  misc/docker/run.sh pytest mypyc/
+"""
+
+import argparse
+import os
+import subprocess
+import sys
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="""Build a 'mypy-test' Docker container for running mypy/mypyc tests. You may
+                       need to run this as root (using sudo)."""
+    )
+    parser.add_argument("--no-cache", action="store_true", help="Force rebuilding")
+    parser.add_argument("--pull", action="store_true", help="Force pulling fresh Linux base image")
+    args = parser.parse_args()
+
+    dockerdir = os.path.dirname(os.path.abspath(__file__))
+    dockerfile = os.path.join(dockerdir, "Dockerfile")
+    rootdir = os.path.join(dockerdir, "..", "..")
+
+    cmdline = ["docker", "build", "-t", "mypy-test", "-f", dockerfile]
+    if args.no_cache:
+        cmdline.append("--no-cache")
+    if args.pull:
+        cmdline.append("--pull")
+    cmdline.append(rootdir)
+    result = subprocess.run(cmdline)
+    sys.exit(result.returncode)
+
+
+if __name__ == "__main__":
+    main()


Test patch:
Repository: python/mypy

Issue:
Unbound type variable false positive with six.with_metaclass
This code generates a false positive:
```py
import six
import abc
from typing import TypeVar, Generic

T = TypeVar("T")

class C(six.with_metaclass(abc.ABCMeta, Generic[T])):
    pass

class D(six.with_metaclass(abc.ABCMeta, C[T])):  # Type variable "t.T" is unbound
    pass
```
This is a regression from 0.991 introduced here:
* #14159

@ilevkivskyi Do you have time to look at this? This is a blocker for the 1.0 release.


Discussion:

Resolving patch:
diff --git a/mypy/semanal.py b/mypy/semanal.py
--- a/mypy/semanal.py
+++ b/mypy/semanal.py
@@ -2181,7 +2181,7 @@ def infer_metaclass_and_bases_from_compat_helpers(self, defn: ClassDef) -> None:
         if len(defn.base_type_exprs) == 1:
             base_expr = defn.base_type_exprs[0]
             if isinstance(base_expr, CallExpr) and isinstance(base_expr.callee, RefExpr):
-                base_expr.accept(self)
+                self.analyze_type_expr(base_expr)
                 if (
                     base_expr.callee.fullname
                     in {


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
@@ -5293,6 +5293,19 @@ class F(six.with_metaclass(t.M)): pass
 class G: pass
 [builtins fixtures/tuple.pyi]
 
+[case testSixMetaclassGenericBase]
+import six
+import abc
+from typing import TypeVar, Generic
+
+T = TypeVar("T")
+
+class C(six.with_metaclass(abc.ABCMeta, Generic[T])):
+    pass
+class D(six.with_metaclass(abc.ABCMeta, C[T])):
+    pass
+[builtins fixtures/tuple.pyi]
+
 -- Special support for future.utils
 -- --------------------------------
Repository: python/mypy

Issue:
`Expected type in class pattern; found "Any"` for ignored missing import in match/case
**To Reproduce**

```python
from somewhere import Foo

match None:
    case Foo():
        ...
```

https://mypy-play.net/?mypy=latest&python=3.11&flags=ignore-missing-imports&gist=03694364e4e855575f23ba9c625e804e

**Expected Behavior**

no error


**Actual Behavior**

```
$ mypy --ignore-missing-imports test.py
test.py:4: error: Expected type in class pattern; found "Any"  [misc]
Found 1 error in 1 file (checked 1 source file)
```

**Your Environment**

mypy 0.991 without config files on python 3.10 and 3.11



Discussion:

Resolving patch:
diff --git a/mypy/checkpattern.py b/mypy/checkpattern.py
--- a/mypy/checkpattern.py
+++ b/mypy/checkpattern.py
@@ -457,6 +457,12 @@ def visit_class_pattern(self, o: ClassPattern) -> PatternType:
             typ: Type = Instance(type_info, [any_type] * len(type_info.defn.type_vars))
         elif isinstance(type_info, TypeAlias):
             typ = type_info.target
+        elif (
+            isinstance(type_info, Var)
+            and type_info.type is not None
+            and isinstance(get_proper_type(type_info.type), AnyType)
+        ):
+            typ = type_info.type
         else:
             if isinstance(type_info, Var):
                 name = str(type_info.type)


Test patch:
diff --git a/test-data/unit/check-python310.test b/test-data/unit/check-python310.test
--- a/test-data/unit/check-python310.test
+++ b/test-data/unit/check-python310.test
@@ -896,6 +896,16 @@ match m:
         reveal_type(i)
         reveal_type(j)
 
+[case testMatchClassPatternAny]
+from typing import Any
+
+Foo: Any
+m: object
+
+match m:
+    case Foo():
+        pass
+
 [case testMatchClassPatternNestedGenerics]
 # From cpython test_patma.py
 x = [[{0: 0}]]
Repository: python/mypy

Issue:
`TypeVar` with values has incompatible type when used `Self`
**Bug Report**

I'm not sure what's going on, better check the example. Also mypy experts, please forgive me if this is intentional behavior and not a bug.

**To Reproduce**

```python
import typing

class A: pass
class B: pass

T = typing.TypeVar('T', A, B)

class C(typing.Generic[T]):

    def method_A(self, argument: T) -> None: pass

    def method_C(self, argument: T) -> typing.Self:
        self.method_A(argument)
        return self
```

**Actual Behavior**

```
main.py:13: error: Argument 1 to "method_A" of "C" has incompatible type "A"; expected "T"  [arg-type]
main.py:13: error: Argument 1 to "method_A" of "C" has incompatible type "B"; expected "T"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)
```

**Your Environment**

- Mypy version used: mypy 1.0.0+dev.9183b28401bd2928d921a068bbbc7e6565e77649 (compiled: no)
- Mypy command-line flags: none required to reproduce
- Mypy configuration options from `mypy.ini` (and other config files): none required to reproduce
- Python version used: 3.11


Discussion:

Resolving patch:
diff --git a/mypy/expandtype.py b/mypy/expandtype.py
--- a/mypy/expandtype.py
+++ b/mypy/expandtype.py
@@ -222,6 +222,10 @@ def visit_instance(self, t: Instance) -> Type:
             return args
 
     def visit_type_var(self, t: TypeVarType) -> Type:
+        # Normally upper bounds can't contain other type variables, the only exception is
+        # special type variable Self`0 <: C[T, S], where C is the class where Self is used.
+        if t.id.raw_id == 0:
+            t = t.copy_modified(upper_bound=t.upper_bound.accept(self))
         repl = self.variables.get(t.id, t)
         if isinstance(repl, ProperType) and isinstance(repl, Instance):
             # TODO: do we really need to do this?


Test patch:
diff --git a/test-data/unit/check-selftype.test b/test-data/unit/check-selftype.test
--- a/test-data/unit/check-selftype.test
+++ b/test-data/unit/check-selftype.test
@@ -1785,3 +1785,23 @@ class C(B, Generic[T]):
         inst = super().copy()
         reveal_type(inst)  # N: Revealed type is "Self`0"
         return inst
+
+[case testTypingSelfWithValuesExpansion]
+from typing import Self, Generic, TypeVar
+
+class A: pass
+class B: pass
+T = TypeVar("T", A, B)
+
+class C(Generic[T]):
+    val: T
+    def foo(self, x: T) -> None: ...
+    def bar(self, x: T) -> Self:
+        reveal_type(self.foo)  # N: Revealed type is "def (x: __main__.A)" \
+                               # N: Revealed type is "def (x: __main__.B)"
+        self.foo(x)
+        return self
+    def baz(self: Self, x: T) -> None:
+        reveal_type(self.val)  # N: Revealed type is "__main__.A" \
+                               # N: Revealed type is "__main__.B"
+        self.val = x
Repository: python/mypy

Issue:
stubgen crash when a referenced module is a DLL
<!--
  Use this form only if mypy reports an "INTERNAL ERROR" and/or gives a traceback.
  Please include the traceback and all other messages below (use `mypy --show-traceback`).
-->

**Crash Report**
Same as #13822 (https://github.com/python/mypy/issues/13822#issuecomment-1269097692), but for stubgen. I've just tried it out in 0.990
stubgen crashes when a referenced module is a DLL, as it seemingly tries to parse the `.dll`'s content as text.

**Traceback**

```
PS C:\Users\Avasam\Documents\Git\typeshed> stubgen -p pywintypes
Critical error during semantic analysis: mypy: can't decode file 'C:\Users\Avasam\Documents\Git\typeshed\.venv\Lib\site-packages\pywin32_system32\pywintypes39.dll': 'utf-8' codec can't decode byte 0x90 in position 2: invalid start byte
```

**To Reproduce**
`pip install pywin32`
`stubgen -p pywintypes`

**Your Environment**

<!-- Include as many relevant details about the environment you experienced the bug in -->

- Mypy version used: 0.990 (compiled: yes)
- Mypy command-line flags: (see above)
- Mypy configuration options from `mypy.ini` (and other config files): (see above)
- Python version used: 3.9.13
- Operating system and version: Windows 10.0.19044 Build 19044


<!--
You can freely edit this text, please remove all the lines
you believe are unnecessary.
-->



Discussion:
Thanks, want to make a PR? :-)
Given how simple the fix you did for stubtest was, sure, I can try it out.

Resolving patch:
diff --git a/mypy/moduleinspect.py b/mypy/moduleinspect.py
--- a/mypy/moduleinspect.py
+++ b/mypy/moduleinspect.py
@@ -36,7 +36,7 @@ def is_c_module(module: ModuleType) -> bool:
         # Could be a namespace package. These must be handled through
         # introspection, since there is no source file.
         return True
-    return os.path.splitext(module.__dict__["__file__"])[-1] in [".so", ".pyd"]
+    return os.path.splitext(module.__dict__["__file__"])[-1] in [".so", ".pyd", ".dll"]
 
 
 class InspectError(Exception):


Test patch:
Repository: python/mypy

Issue:
Stubgen crashes on new Python 3.10 union syntax
<!--
  Use this form only if mypy reports an "INTERNAL ERROR" and/or gives a traceback.
  Please include the traceback and all other messages below (use `mypy --show-traceback`).
-->

**Crash Report**

It works in some cases e.g. with `cast()` function but here with `TypeVar` it crashes.

Mypy accepts this file with no errors.

**Traceback**

```
  File "mypy/stubgen.py", line 1858, in main
  File "mypy/stubgen.py", line 1701, in generate_stubs
  File "mypy/stubgen.py", line 1643, in generate_stub_from_ast
  File "mypy/nodes.py", line 373, in accept
  File "mypy/stubgen.py", line 643, in visit_mypy_file
  File "mypy/traverser.py", line 114, in visit_mypy_file
  File "mypy/nodes.py", line 1301, in accept
  File "mypy/stubgen.py", line 1006, in visit_assignment_stmt
  File "mypy/stubgen.py", line 1117, in process_typealias
  File "mypy/nodes.py", line 1841, in accept
  File "mypy/stubgen.py", line 362, in visit_call_expr
TypeError: str object expected; got None
```

**To Reproduce**

```python3
from __future__ import annotations

from typing import TypeVar

T = TypeVar("T", bound=str | None)
```

**Your Environment**

<!-- Include as many relevant details about the environment you experienced the bug in -->

- Mypy version used: 0.991
- Mypy command-line flags: `stubgen test.py`
- Mypy configuration options from `mypy.ini` (and other config files):
- Python version used: 3.10.9
- Operating system and version: macOS

<!--
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
@@ -95,6 +95,7 @@
     MemberExpr,
     MypyFile,
     NameExpr,
+    OpExpr,
     OverloadedFuncDef,
     Statement,
     StrExpr,
@@ -402,6 +403,9 @@ def visit_list_expr(self, node: ListExpr) -> str:
     def visit_ellipsis(self, node: EllipsisExpr) -> str:
         return "..."
 
+    def visit_op_expr(self, o: OpExpr) -> str:
+        return f"{o.left.accept(self)} {o.op} {o.right.accept(self)}"
+
 
 class ImportTracker:
     """Record necessary imports during stub generation."""


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
@@ -2734,3 +2734,12 @@ class Some:
     def __int__(self) -> int: ...
     def __float__(self) -> float: ...
     def __index__(self) -> int: ...
+
+
+[case testTypeVarPEP604Bound]
+from typing import TypeVar
+T = TypeVar("T", bound=str | None)
+[out]
+from typing import TypeVar
+
+T = TypeVar('T', bound=str | None)
Repository: python/mypy

Issue:
stubgen: import `Union` if generated stub code includes
**Feature**

I would like to insert `from typing import Union` when generated stub code by stubgen includes `Union`.

**Pitch**

ref: #12920

Now:

```shellsession
# Python 3.10.4, mypy 0.960
$ cat test.py
import random


def a() -> int | str:
    if random.random() > 0.5:
        return 1
    else:
        return "hey!"

def b() -> str | None:
    if random.random() > 0.5:
        return "hey!"

$ stubgen test.py
Processed 1 modules
Generated out/test.pyi

$ cat out/test.pyi
def a() -> Union[int, str]: ...
def b() -> Union[str, None]: ...
```

Expect:

```python
from typing import Union

def a() -> Union[int, str]: ...
def b() -> Union[str, None]: ...
```
Add import Union to stub file (#12929)
Fixes #12929

Stubs generated from files with new format of Union typing will include importing Union from typing.

## Test Plan

I've added 3 new tests while making sure they pass locally.



Discussion:
Thanks! I expect this is an easy fix (just need to ad some function call to make stubgen emit the import), so if you're willing to dive into the code, feel free to make a PR.
OK, I'll try it...
Is there any update on this fix?
I've fixed the formatting and failing test :-)

Resolving patch:
diff --git a/mypy/stubgen.py b/mypy/stubgen.py
--- a/mypy/stubgen.py
+++ b/mypy/stubgen.py
@@ -134,6 +134,7 @@
     TypeList,
     TypeStrVisitor,
     UnboundType,
+    UnionType,
     get_proper_type,
 )
 from mypy.visitor import NodeVisitor
@@ -326,6 +327,9 @@ def visit_none_type(self, t: NoneType) -> str:
     def visit_type_list(self, t: TypeList) -> str:
         return f"[{self.list_str(t.items)}]"
 
+    def visit_union_type(self, t: UnionType) -> str:
+        return " | ".join([item.accept(self) for item in t.items])
+
     def args_str(self, args: Iterable[Type]) -> str:
         """Convert an array of arguments to strings and join the results with commas.
 


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
@@ -2783,3 +2783,13 @@ T = TypeVar("T", bound=str | None)
 from typing import TypeVar
 
 T = TypeVar('T', bound=str | None)
+
+
+[case testPEP604UnionType]
+a: str | int
+
+def f(x: str | None) -> None: ...
+[out]
+a: str | int
+
+def f(x: str | None) -> None: ...
Repository: python/mypy

Issue:
Reusing variable previously defined with walrus operator triggers used-before-def error
**To Reproduce**

```python
x = 3
z = (y := str(x)).index(y.lower())
```

**Expected Behavior**

Should be no errors -- this code does not error using mypy v0.991 or prior, so this seems to be a new issue with v1.0.0.

**Actual Behavior**

```error: Name "y" is used before definition  [used-before-def]```

**Your Environment**

- Mypy version used: 1.0.0
- Mypy command-line flags: none
- Python version used: 3.9




Discussion:

Resolving patch:
diff --git a/mypy/traverser.py b/mypy/traverser.py
--- a/mypy/traverser.py
+++ b/mypy/traverser.py
@@ -253,9 +253,9 @@ def visit_yield_expr(self, o: YieldExpr) -> None:
             o.expr.accept(self)
 
     def visit_call_expr(self, o: CallExpr) -> None:
+        o.callee.accept(self)
         for a in o.args:
             a.accept(self)
-        o.callee.accept(self)
         if o.analyzed:
             o.analyzed.accept(self)
 


Test patch:
diff --git a/test-data/unit/check-python38.test b/test-data/unit/check-python38.test
--- a/test-data/unit/check-python38.test
+++ b/test-data/unit/check-python38.test
@@ -573,6 +573,14 @@ def foo() -> None:
     [x := x + y for y in [1, 2, 3]]
 [builtins fixtures/dict.pyi]
 
+[case testWalrusUsedBeforeDef]
+# flags: --python-version 3.8
+class C:
+    def f(self, c: 'C') -> None: pass
+
+(x := C()).f(y)  # E: Cannot determine type of "y"  # E: Name "y" is used before definition
+(y := C()).f(y)
+
 [case testOverloadWithPositionalOnlySelf]
 # flags: --python-version 3.8
 from typing import overload, Optional
Repository: python/mypy

Issue:
Reusing variable previously defined with walrus operator triggers used-before-def error
**To Reproduce**

```python
x = 3
z = (y := str(x)).index(y.lower())
```

**Expected Behavior**

Should be no errors -- this code does not error using mypy v0.991 or prior, so this seems to be a new issue with v1.0.0.

**Actual Behavior**

```error: Name "y" is used before definition  [used-before-def]```

**Your Environment**

- Mypy version used: 1.0.0
- Mypy command-line flags: none
- Python version used: 3.9




Discussion:
Thanks for reporting! We will include the fix in the 1.0.1 release.

Resolving patch:
diff --git a/mypy/traverser.py b/mypy/traverser.py
--- a/mypy/traverser.py
+++ b/mypy/traverser.py
@@ -253,9 +253,9 @@ def visit_yield_expr(self, o: YieldExpr) -> None:
             o.expr.accept(self)
 
     def visit_call_expr(self, o: CallExpr) -> None:
+        o.callee.accept(self)
         for a in o.args:
             a.accept(self)
-        o.callee.accept(self)
         if o.analyzed:
             o.analyzed.accept(self)
 


Test patch:
diff --git a/test-data/unit/check-python38.test b/test-data/unit/check-python38.test
--- a/test-data/unit/check-python38.test
+++ b/test-data/unit/check-python38.test
@@ -573,6 +573,14 @@ def foo() -> None:
     [x := x + y for y in [1, 2, 3]]
 [builtins fixtures/dict.pyi]
 
+[case testWalrusUsedBeforeDef]
+# flags: --python-version 3.8
+class C:
+    def f(self, c: 'C') -> None: pass
+
+(x := C()).f(y)  # E: Cannot determine type of "y"  # E: Name "y" is used before definition
+(y := C()).f(y)
+
 [case testOverloadWithPositionalOnlySelf]
 # flags: --python-version 3.8
 from typing import overload, Optional