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

Issue:
Instances of type variables bounded by an iterable type support iteration but not unpacking
**Bug Report**

Instances of type variables bounded by an iterable type support iteration but not unpacking.

**To Reproduce**

```python
from typing import TypeVar

class A:
    pass

ATuple = TypeVar("ATuple", bound=tuple[A, ...])

def f(aa: ATuple) -> None:
    for a in aa:               # this is ok
        print(a)

f((A(),))

def g(aa: ATuple) -> None:
    (a,) = aa                  # "ATuple" object is not iterable
    print(a)

g((A(),))
```

Bounding the TypeVar by `list[A]` has the same behaviour as bounding it by `tuple[A, ...]`.

**Expected Behavior**

No error -- an ATuple should support both iteration and unpacking.

**Actual Behavior**

f() checks clean.

In g(), unpacking fails with:

error: "ATuple" object is not iterable
error: Cannot determine type of "a"

**Your Environment**

This reproduces in all versions in the playground.


Discussion:

Resolving patch:
diff --git a/mypy/checker.py b/mypy/checker.py
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -3168,6 +3168,9 @@ def check_multi_assignment(
         # TODO: maybe elsewhere; redundant.
         rvalue_type = get_proper_type(rv_type or self.expr_checker.accept(rvalue))
 
+        if isinstance(rvalue_type, TypeVarType):
+            rvalue_type = get_proper_type(rvalue_type.upper_bound)
+
         if isinstance(rvalue_type, UnionType):
             # If this is an Optional type in non-strict Optional code, unwrap it.
             relevant_items = rvalue_type.relevant_items()


Test patch:
diff --git a/test-data/unit/check-bound.test b/test-data/unit/check-bound.test
--- a/test-data/unit/check-bound.test
+++ b/test-data/unit/check-bound.test
@@ -215,3 +215,13 @@ if int():
     b = 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
 twice(a) # E: Value of type variable "T" of "twice" cannot be "int"
 [builtins fixtures/args.pyi]
+
+
+[case testIterableBoundUnpacking]
+from typing import Tuple, TypeVar
+TupleT = TypeVar("TupleT", bound=Tuple[int, ...])
+def f(t: TupleT) -> None:
+    a, *b = t
+    reveal_type(a)  # N: Revealed type is "builtins.int"
+    reveal_type(b)  # N: Revealed type is "builtins.list[builtins.int]"
+[builtins fixtures/tuple.pyi]
diff --git a/test-data/unit/check-typevar-unbound.test b/test-data/unit/check-typevar-unbound.test
--- a/test-data/unit/check-typevar-unbound.test
+++ b/test-data/unit/check-typevar-unbound.test
@@ -58,3 +58,9 @@ def h(a: List[Union[Callable[..., T]]]) -> T:
 def j(a: List[Union[Callable[..., Tuple[T, T]], int]]) -> T:
     ...
 [builtins fixtures/tuple.pyi]
+
+[case testUnboundedTypevarUnpacking]
+from typing import TypeVar
+T = TypeVar("T")
+def f(t: T) -> None:
+    a, *b = t  # E: "object" object is not iterable
Repository: python/mypy

Issue:
"Trying to read deleted variable" false negative when deleting class
```py
class Foo: ...
del Foo

print(Foo) # no error
```
[playground](https://mypy-play.net/?mypy=latest&python=3.10&flags=show-error-context%2Cshow-error-codes%2Cstrict%2Ccheck-untyped-defs%2Cdisallow-any-decorated%2Cdisallow-any-expr%2Cdisallow-any-explicit%2Cdisallow-any-generics%2Cdisallow-any-unimported%2Cdisallow-incomplete-defs%2Cdisallow-subclassing-any%2Cdisallow-untyped-calls%2Cdisallow-untyped-decorators%2Cdisallow-untyped-defs%2Cno-implicit-optional%2Cno-implicit-reexport%2Clocal-partial-types%2Cstrict-equality%2Cwarn-incomplete-stub%2Cwarn-redundant-casts%2Cwarn-return-any%2Cwarn-unreachable%2Cwarn-unused-configs%2Cwarn-unused-ignores&gist=1dea89d07b0f24e562595bf221e4f7d8)


Discussion:

Resolving patch:
diff --git a/mypy/binder.py b/mypy/binder.py
--- a/mypy/binder.py
+++ b/mypy/binder.py
@@ -8,9 +8,28 @@
 from mypy.erasetype import remove_instance_last_known_values
 from mypy.join import join_simple
 from mypy.literals import Key, literal, literal_hash, subkeys
-from mypy.nodes import AssignmentExpr, Expression, IndexExpr, MemberExpr, NameExpr, RefExpr, Var
+from mypy.nodes import (
+    AssignmentExpr,
+    Expression,
+    IndexExpr,
+    MemberExpr,
+    NameExpr,
+    RefExpr,
+    TypeInfo,
+    Var,
+)
 from mypy.subtypes import is_same_type, is_subtype
-from mypy.types import AnyType, NoneType, PartialType, Type, TypeOfAny, UnionType, get_proper_type
+from mypy.types import (
+    AnyType,
+    NoneType,
+    PartialType,
+    Type,
+    TypeOfAny,
+    TypeType,
+    UnionType,
+    get_proper_type,
+)
+from mypy.typevars import fill_typevars_with_any
 
 BindableExpression: _TypeAlias = Union[IndexExpr, MemberExpr, AssignmentExpr, NameExpr]
 
@@ -439,8 +458,11 @@ def top_frame_context(self) -> Iterator[Frame]:
 
 
 def get_declaration(expr: BindableExpression) -> Type | None:
-    if isinstance(expr, RefExpr) and isinstance(expr.node, Var):
-        type = expr.node.type
-        if not isinstance(get_proper_type(type), PartialType):
-            return type
+    if isinstance(expr, RefExpr):
+        if isinstance(expr.node, Var):
+            type = expr.node.type
+            if not isinstance(get_proper_type(type), PartialType):
+                return type
+        elif isinstance(expr.node, TypeInfo):
+            return TypeType(fill_typevars_with_any(expr.node))
     return None


Test patch:
diff --git a/test-data/unit/check-statements.test b/test-data/unit/check-statements.test
--- a/test-data/unit/check-statements.test
+++ b/test-data/unit/check-statements.test
@@ -1073,6 +1073,10 @@ a = A()
 del a.x, a.y # E: "A" has no attribute "y"
 [builtins fixtures/tuple.pyi]
 
+[case testDelStmtWithTypeInfo]
+class Foo: ...
+del Foo
+Foo + 1  # E: Trying to read deleted variable "Foo"
 
 [case testDelStatementWithAssignmentSimple]
 a = 1
Repository: python/mypy

Issue:
pypy3.9 -  SyntaxError due to positional only arguments in stubfile
**Bug Report**

Typecheck a *.pyi file containing a function with positional only arguments raises a SyntaxError.
I use pypy3.9 (with pypy3.8 i don't get any errors)

**To Reproduce**

Run the code below with mypy and pypy3.9

```python
def f(a:int, b:int, /) -> None:
	...
```

**Expected Behavior**

No error

**Actual Behavior**

```bash
SyntaxError: Positional only arguments are only supported in Python (3, 8) and above.
```
I guess the reason is that when parsing a stubfile the feature_version 7 is used. 
Running the code with feature_version 8 solves the problem

**Your Environment**

- Mypy version used: mypy 0.971 (compiled: no)
- Python version used:
```
Python 3.9.12 | packaged by conda-forge | (05fbe3aa, Aug 15 2022, 10:20:11)
[PyPy 7.3.9 with GCC 10.4.0]
```
- Operating system and version: Ubuntu


Discussion:

Resolving patch:
diff --git a/mypy/fastparse.py b/mypy/fastparse.py
--- a/mypy/fastparse.py
+++ b/mypy/fastparse.py
@@ -267,6 +267,8 @@ def parse(
     is_stub_file = fnam.endswith(".pyi")
     if is_stub_file:
         feature_version = defaults.PYTHON3_VERSION[1]
+        if options.python_version[0] == 3 and options.python_version[1] > feature_version:
+            feature_version = options.python_version[1]
     else:
         assert options.python_version[0] >= 3
         feature_version = options.python_version[1]


Test patch:
Repository: python/mypy

Issue:
Conditional `def` not understood as assignment
Under `--strict-optional`, the following yields an error:

```
    f = None  # type: Optional[Callable[[], None]]
    if f is None:
        def f():
            pass
    f()  # error: None not callable
```

If the `def` within the conditional is replaced by `f = lambda: None`, there is no error.


Discussion:

Resolving patch:
diff --git a/mypy/checker.py b/mypy/checker.py
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -980,7 +980,9 @@ def _visit_func_def(self, defn: FuncDef) -> None:
                         # Trying to redefine something like partial empty list as function.
                         self.fail(message_registry.INCOMPATIBLE_REDEFINITION, defn)
                 else:
-                    # TODO: Update conditional type binder.
+                    name_expr = NameExpr(defn.name)
+                    name_expr.node = defn.original_def
+                    self.binder.assign_type(name_expr, new_type, orig_type)
                     self.check_subtype(
                         new_type,
                         orig_type,


Test patch:
diff --git a/test-data/unit/check-narrowing.test b/test-data/unit/check-narrowing.test
--- a/test-data/unit/check-narrowing.test
+++ b/test-data/unit/check-narrowing.test
@@ -1249,3 +1249,14 @@ def two_type_vars(x: Union[str, Dict[str, int], Dict[bool, object], int]) -> Non
     else:
         reveal_type(x)  # N: Revealed type is "builtins.int"
 [builtins fixtures/dict.pyi]
+
+
+[case testNarrowingWithDef]
+from typing import Callable, Optional
+
+def g() -> None:
+    foo: Optional[Callable[[], None]] = None
+    if foo is None:
+        def foo(): ...
+    foo()
+[builtins fixtures/dict.pyi]
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
@@ -5986,10 +5986,10 @@ reveal_type(f2(A()))  # E: No overload variant of "f2" matches argument type "A"
 if True:
     @overload  # E: Single overload definition, multiple required
     def f3(x: A) -> A: ...
+    def f3(x): ...
     if maybe_true:  # E: Name "maybe_true" is not defined
         @overload  # E: Single overload definition, multiple required
         def g3(x: B) -> B: ...
-    def f3(x): ...
 reveal_type(f3(A()))  # N: Revealed type is "__main__.A"
 
 if True:
Repository: python/mypy

Issue:
`ABCMeta` and its subclasses are treated differently
It is a common practice to create subclasses of `ABCMeta` for your own abstract metaclasses when you also have other metaclass(es). It helps solving metaclass conflict error.

For example:

```python
from djang.db.models import ModelBase
from abc import ABCMeta

class AbstractModel(ABCMeta, ModelBase): ...
```

Or any other existing metaclass.

But, mypy treats `ABCMeta` and `AbstractModel` differently:

```python
from abc import ABCMeta, abstractmethod
from typing import Protocol

class A:  # OK, has @abstractmethod
    @abstractmethod
    def f(self) -> None:
        pass

# Expected:
class B(A):  # E: Class a.B has abstract attributes "f"  # N: If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass
    pass

class C(A, metaclass=ABCMeta):  # OK, has ABCMeta as a metaclass
    pass

class CustomABC(ABCMeta):
    pass

# Unexpected:
class D(A, metaclass=CustomABC):  # E: Class a.D has abstract attributes "f"  # N: If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass
    pass
```

I think that needs to be fixed.


Discussion:

Resolving patch:
diff --git a/mypy/semanal_classprop.py b/mypy/semanal_classprop.py
--- a/mypy/semanal_classprop.py
+++ b/mypy/semanal_classprop.py
@@ -95,7 +95,7 @@ def calculate_class_abstract_status(typ: TypeInfo, is_stub_file: bool, errors: E
     # implement some methods.
     typ.abstract_attributes = sorted(abstract)
     if is_stub_file:
-        if typ.declared_metaclass and typ.declared_metaclass.type.fullname == "abc.ABCMeta":
+        if typ.declared_metaclass and typ.declared_metaclass.type.has_base("abc.ABCMeta"):
             return
         if typ.is_protocol:
             return


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
@@ -5497,6 +5497,13 @@ class E(Protocol):  # OK, is a protocol
 class F(E, Protocol):  # OK, is a protocol
     pass
 
+# Custom metaclass subclassing `ABCMeta`, see #13561
+class CustomMeta(ABCMeta):
+    pass
+
+class G(A, metaclass=CustomMeta):  # Ok, has CustomMeta as a metaclass
+    pass
+
 [file b.py]
 # All of these are OK because this is not a stub file.
 from abc import ABCMeta, abstractmethod
@@ -5525,6 +5532,12 @@ class E(Protocol):
 class F(E, Protocol):
     pass
 
+class CustomMeta(ABCMeta):
+    pass
+
+class G(A, metaclass=CustomMeta):
+    pass
+
 [case testClassMethodOverride]
 from typing import Callable, Any
Repository: python/mypy

Issue:
Instances of type variables bounded by an iterable type support iteration but not unpacking
**Bug Report**

Instances of type variables bounded by an iterable type support iteration but not unpacking.

**To Reproduce**

```python
from typing import TypeVar

class A:
    pass

ATuple = TypeVar("ATuple", bound=tuple[A, ...])

def f(aa: ATuple) -> None:
    for a in aa:               # this is ok
        print(a)

f((A(),))

def g(aa: ATuple) -> None:
    (a,) = aa                  # "ATuple" object is not iterable
    print(a)

g((A(),))
```

Bounding the TypeVar by `list[A]` has the same behaviour as bounding it by `tuple[A, ...]`.

**Expected Behavior**

No error -- an ATuple should support both iteration and unpacking.

**Actual Behavior**

f() checks clean.

In g(), unpacking fails with:

error: "ATuple" object is not iterable
error: Cannot determine type of "a"

**Your Environment**

This reproduces in all versions in the playground.


Discussion:

Resolving patch:
diff --git a/mypy/checker.py b/mypy/checker.py
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -3173,6 +3173,9 @@ def check_multi_assignment(
         # TODO: maybe elsewhere; redundant.
         rvalue_type = get_proper_type(rv_type or self.expr_checker.accept(rvalue))
 
+        if isinstance(rvalue_type, TypeVarType):
+            rvalue_type = get_proper_type(rvalue_type.upper_bound)
+
         if isinstance(rvalue_type, UnionType):
             # If this is an Optional type in non-strict Optional code, unwrap it.
             relevant_items = rvalue_type.relevant_items()


Test patch:
diff --git a/test-data/unit/check-bound.test b/test-data/unit/check-bound.test
--- a/test-data/unit/check-bound.test
+++ b/test-data/unit/check-bound.test
@@ -215,3 +215,13 @@ if int():
     b = 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
 twice(a) # E: Value of type variable "T" of "twice" cannot be "int"
 [builtins fixtures/args.pyi]
+
+
+[case testIterableBoundUnpacking]
+from typing import Tuple, TypeVar
+TupleT = TypeVar("TupleT", bound=Tuple[int, ...])
+def f(t: TupleT) -> None:
+    a, *b = t
+    reveal_type(a)  # N: Revealed type is "builtins.int"
+    reveal_type(b)  # N: Revealed type is "builtins.list[builtins.int]"
+[builtins fixtures/tuple.pyi]
diff --git a/test-data/unit/check-typevar-unbound.test b/test-data/unit/check-typevar-unbound.test
--- a/test-data/unit/check-typevar-unbound.test
+++ b/test-data/unit/check-typevar-unbound.test
@@ -58,3 +58,9 @@ def h(a: List[Union[Callable[..., T]]]) -> T:
 def j(a: List[Union[Callable[..., Tuple[T, T]], int]]) -> T:
     ...
 [builtins fixtures/tuple.pyi]
+
+[case testUnboundedTypevarUnpacking]
+from typing import TypeVar
+T = TypeVar("T")
+def f(t: T) -> None:
+    a, *b = t  # E: "object" object is not iterable
Repository: python/mypy

Issue:
stubtest `--custom-typeshed-dir` broken on master and 0.980
**Bug Report**

https://github.com/python/mypy/commit/c0372cc318dc35b25d4fe524b59f20b1244382a3 appears to have broken stubtest if you use it with `--custom-typeshed-dir`. Attempting to use stubtest with `--custom-typeshed-dir` pointing to a local clone of typeshed will result in the following message (or something like it):

```
error: not checking stubs due to failed mypy compile:
mypy: "..\typeshed\stdlib\builtins.pyi" shadows library module "builtins"
note: A user-defined top-level module with name "builtins" is not supported
```

Notes on the bug:

- I haven't been able to reproduce this using "mypy core", only with stubtest.
- The bug exists on both mypy `master` and mypy `release-0.980`.
- The bug exists if you use a relative path or an absolute path to point to a clone of typeshed.
- The bug exists if you use the `--check-typeshed` flag, as well as if you don't.
- I bisected to https://github.com/python/mypy/commit/c0372cc318dc35b25d4fe524b59f20b1244382a3 (https://github.com/python/mypy/pull/13629)

Cc. @ilevkivskyi, @jhance, @hauntsaninja

**To Reproduce**

Any of the following will reproduce:

- `(venv) python -m mypy.stubtest typed_ast --custom-typeshed-dir relative/path/to/typeshed`
- `(venv) python -m mypy.stubtest typed_ast --custom-typeshed-dir absolute/path/to/typeshed`
- `(venv) python -m mypy.stubtest --check-typeshed --custom-typeshed-dir relative/path/to/typeshed`
- `(venv) python -m mypy.stubtest --check-typeshed --custom-typeshed-dir absolute/path/to/typeshed`

**Expected Behavior**

Stubtest with `--custom-typeshed-dir` would work on mypy master.

**Actual Behavior**

Stubtest with `--custom-typeshed-dir` did not work on mypy master.

**Your Environment**

- Python version used: 3.10.6
- Operating system and version: Windows



Discussion:

Resolving patch:
diff --git a/mypy/stubtest.py b/mypy/stubtest.py
--- a/mypy/stubtest.py
+++ b/mypy/stubtest.py
@@ -1597,6 +1597,8 @@ def test_stubs(args: _Arguments, use_builtins_fixtures: bool = False) -> int:
     options = Options()
     options.incremental = False
     options.custom_typeshed_dir = args.custom_typeshed_dir
+    if options.custom_typeshed_dir:
+        options.abs_custom_typeshed_dir = os.path.abspath(args.custom_typeshed_dir)
     options.config_file = args.mypy_config_file
     options.use_builtins_fixtures = use_builtins_fixtures
 


Test patch:
Repository: python/mypy

Issue:
stubtest `--custom-typeshed-dir` broken on master and 0.980
**Bug Report**

https://github.com/python/mypy/commit/c0372cc318dc35b25d4fe524b59f20b1244382a3 appears to have broken stubtest if you use it with `--custom-typeshed-dir`. Attempting to use stubtest with `--custom-typeshed-dir` pointing to a local clone of typeshed will result in the following message (or something like it):

```
error: not checking stubs due to failed mypy compile:
mypy: "..\typeshed\stdlib\builtins.pyi" shadows library module "builtins"
note: A user-defined top-level module with name "builtins" is not supported
```

Notes on the bug:

- I haven't been able to reproduce this using "mypy core", only with stubtest.
- The bug exists on both mypy `master` and mypy `release-0.980`.
- The bug exists if you use a relative path or an absolute path to point to a clone of typeshed.
- The bug exists if you use the `--check-typeshed` flag, as well as if you don't.
- I bisected to https://github.com/python/mypy/commit/c0372cc318dc35b25d4fe524b59f20b1244382a3 (https://github.com/python/mypy/pull/13629)

Cc. @ilevkivskyi, @jhance, @hauntsaninja

**To Reproduce**

Any of the following will reproduce:

- `(venv) python -m mypy.stubtest typed_ast --custom-typeshed-dir relative/path/to/typeshed`
- `(venv) python -m mypy.stubtest typed_ast --custom-typeshed-dir absolute/path/to/typeshed`
- `(venv) python -m mypy.stubtest --check-typeshed --custom-typeshed-dir relative/path/to/typeshed`
- `(venv) python -m mypy.stubtest --check-typeshed --custom-typeshed-dir absolute/path/to/typeshed`

**Expected Behavior**

Stubtest with `--custom-typeshed-dir` would work on mypy master.

**Actual Behavior**

Stubtest with `--custom-typeshed-dir` did not work on mypy master.

**Your Environment**

- Python version used: 3.10.6
- Operating system and version: Windows



Discussion:

Resolving patch:
diff --git a/mypy/stubtest.py b/mypy/stubtest.py
--- a/mypy/stubtest.py
+++ b/mypy/stubtest.py
@@ -1555,6 +1555,8 @@ def test_stubs(args: _Arguments, use_builtins_fixtures: bool = False) -> int:
     options = Options()
     options.incremental = False
     options.custom_typeshed_dir = args.custom_typeshed_dir
+    if options.custom_typeshed_dir:
+        options.abs_custom_typeshed_dir = os.path.abspath(args.custom_typeshed_dir)
     options.config_file = args.mypy_config_file
     options.use_builtins_fixtures = use_builtins_fixtures
 


Test patch:
Repository: python/mypy

Issue:
Defining FORCE_COLOR=true makes mypy fail with traceback
**Bug Report**

This looks like a recent regression as previous versions did not crash when `FORCE_COLOR=true`.

**To Reproduce**

```shell
export FORCE_COLOR=true
mypy ...
```

**Expected Behavior**

To work.

**Actual Behavior**

```
Traceback (most recent call last):
  File "/Users/ssbarnea/.cache/pre-commit/repo79gglgcf/py_env-python3/bin/mypy", line 8, in <module>
    sys.exit(console_entry())
             ^^^^^^^^^^^^^^^
  File "/Users/ssbarnea/.cache/pre-commit/repo79gglgcf/py_env-python3/lib/python3.11/site-packages/mypy/__main__.py", line 15, in console_entry
    main()
  File "mypy/main.py", line 70, in main
  File "mypy/util.py", line 538, in __init__
  File "mypy/util.py", line 523, in should_force_color
ValueError: invalid literal for int() with base 10: 'true'
```

**Your Environment**

<!-- Include as many relevant details about the environment you experienced the bug in -->

- Mypy version used: 0.991
- Mypy command-line flags: --strict
- Mypy configuration options from `mypy.ini` (and other config files):
- Python version used: 3.10

<!-- You can freely edit this text, please remove all the lines you believe are unnecessary. -->



Discussion:

Resolving patch:
diff --git a/mypy/util.py b/mypy/util.py
--- a/mypy/util.py
+++ b/mypy/util.py
@@ -520,7 +520,11 @@ def parse_gray_color(cup: bytes) -> str:
 
 
 def should_force_color() -> bool:
-    return bool(int(os.getenv("MYPY_FORCE_COLOR", os.getenv("FORCE_COLOR", "0"))))
+    env_var = os.getenv("MYPY_FORCE_COLOR", os.getenv("FORCE_COLOR", "0"))
+    try:
+        return bool(int(env_var))
+    except ValueError:
+        return bool(env_var)
 
 
 class FancyFormatter:


Test patch: