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

Issue:
NamedTuple should not satisfy Protocol with mutable fields
The following code doesn't produce a type error, but will crash at runtime, because the named tuple's fields cannot be set

```python
from typing import NamedTuple
from typing_extensions import Protocol

class HasX(Protocol): 
    x: str
    
class A(NamedTuple):
    x: str

a: HasX = A("foo")
a.x = "bar"
```
Since `HasX` requires `x` to be settable, `A` should not be a structural subtype of `HasA`. 





Discussion:
OK, the solution is super-simple here. Since named tuple variables are "artificial" (auto-generated), and therefore are always created directly as a `Var` with `is_property` set to `True`, they are not identified as immutable by protocol check (it looks for a `property` decorator).

So it would be just one line fix in `subtypes.get_member_flags`, we need to add a check for `v.is_property` in this code:
```pthon
    # just a variable
    if isinstance(v, Var):
        flags = {IS_SETTABLE}
```

Would you like to make a PR?
I'll leave that to people smarter than me 😄. 

Resolving patch:
diff --git a/mypy/subtypes.py b/mypy/subtypes.py
--- a/mypy/subtypes.py
+++ b/mypy/subtypes.py
@@ -524,7 +524,7 @@ def get_member_flags(name: str, info: TypeInfo) -> Set[int]:
         if v.var.is_staticmethod or v.var.is_classmethod:
             return {IS_CLASS_OR_STATIC}
     # just a variable
-    if isinstance(v, Var):
+    if isinstance(v, Var) and not v.is_property:
         flags = {IS_SETTABLE}
         if v.is_classvar:
             flags.add(IS_CLASSVAR)


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
@@ -51,6 +51,23 @@ a.y = 5 # E: Property "y" defined in "X" is read-only
 -- a.z = 5 # not supported yet
 
 
+[case testTypingNamedTupleAttributesAreReadOnly]
+from typing import NamedTuple
+from typing_extensions import Protocol
+
+class HasX(Protocol): 
+    x: str
+    
+class A(NamedTuple):
+    x: str
+
+a: HasX = A("foo")
+a.x = "bar"
+[out]
+main:10: error: Incompatible types in assignment (expression has type "A", variable has type "HasX")
+main:10: note: Protocol member HasX.x expected settable variable, got read-only attribute
+
+
 [case testNamedTupleCreateWithPositionalArguments]
 from collections import namedtuple
Repository: python/mypy

Issue:
Module Aliases for PEP 561 not working
Using the mypy's master branch (219fbf890bfbeb03e8720083f4b5850f7fa81636) and pip installing https://github.com/numpy/numpy-stubs (a PEP 561 package), running `mypy` on the following code:

```python
import numpy as np

def f(x: np.ndarray):
    reveal_type(x)
```

outputs:

```
test.py:4: error: Revealed type is 'Any'
```

But if I do:

```python
from numpy import ndarray

def f(x: ndarray):
    reveal_type(x)
```

then I get the expected

```
test.py:4: error: Revealed type is 'numpy.ndarray'
```


Discussion:
Note that this example works perfectly fine with `mypy 0.610`. I ran a git bisect and believe that d91efd46e0b72b6790075244d4e3f37aea171aaf introduced the current behavior.
Confirmed the bisect, and it is happening on master. 

The issue is this part here: https://github.com/python/mypy/blob/master/mypy/semanal.py#L3081. It appears that adding the `__getattr__` check is too earnest, it does not allow for re-binding that occurs on line 3098.

Resolving patch:
diff --git a/mypy/semanal.py b/mypy/semanal.py
--- a/mypy/semanal.py
+++ b/mypy/semanal.py
@@ -3078,7 +3078,7 @@ def lookup_qualified(self, name: str, ctx: Context,
                         n = names.get(parts[i], None)
                         if n and isinstance(n.node, ImportedName):
                             n = self.dereference_module_cross_ref(n)
-                        elif '__getattr__' in names:
+                        elif not n and '__getattr__' in names:
                             gvar = self.create_getattr_var(names['__getattr__'],
                                                            parts[i], parts[i])
                             if gvar:


Test patch:
diff --git a/test-data/unit/check-modules.test b/test-data/unit/check-modules.test
--- a/test-data/unit/check-modules.test
+++ b/test-data/unit/check-modules.test
@@ -2484,3 +2484,14 @@ from typing import Any
 def __getattr__(attr: str) -> Any: ...
 [builtins fixtures/module.pyi]
 [out]
+
+[case testNoGetattrInterference]
+import testmod as t
+def f(x: t.Cls) -> None:
+    reveal_type(x)  # E: Revealed type is 'testmod.Cls'
+[file testmod.pyi]
+from typing import Any
+def __getattr__(attr: str) -> Any: ...
+class Cls: ...
+[builtins fixtures/module.pyi]
+[out]
Repository: python/mypy

Issue:
Error messages about stdlib modules not consistent
Using mypy from master, reporting a usability bug.

Mypy seems to recognize standard library imports:

    /usr/local/lib/python3.6/dist-packages/dns/entropy.py:23: error: No library stub file for standard library module 'dummy_threading'

But when I got an error message about "encodings.idna", I didn't think it was a stdlib module since Mypy used a different wording:

    /usr/local/lib/python3.6/dist-packages/dns/name.py:23: error: Cannot find module named 'encodings.idna'

But encodings.idna is in Python! See https://github.com/python/cpython/blob/master/Lib/encodings/idna.py

Thank you for your patience, I hope the bug report is good, please let me know if you need further information.


Discussion:
Hmm, it looks like the `encodings` module is missing from the list of standard library modules located here -- probably an oversight?

https://github.com/python/mypy/blob/master/mypy/moduleinfo.py

In any case, do you want to try submitting a PR for this? I think the only change you'll need to make is adding the string `"encodings"` to the appropriate list.

(Or alternatively, if you're feeling up to it, you could try contributing stubs for the `encoding` module [to typeshed](https://github.com/python/typeshed). That's a much bigger task though.)

Resolving patch:
diff --git a/mypy/moduleinfo.py b/mypy/moduleinfo.py
--- a/mypy/moduleinfo.py
+++ b/mypy/moduleinfo.py
@@ -270,9 +270,11 @@
     'decimal',
     'difflib',
     'dis',
+    'distutils',
     'doctest',
     'dummy_threading',
     'email',
+    'encodings',
     'fcntl',
     'filecmp',
     'fileinput',


Test patch:
Repository: python/mypy

Issue:
`IntEnum` iterator loses type when passed through `enumerate` or `zip`
I've encountered a typing issue with `IntEnum`. Iterating over the `IntEnum` class works fine until you pass it through a generic function, e.g. `enumerate` or `zip`. Mypy then requests a type annotation, but when I provide it, it fails later with `<nothing>`. This problem does not occur with `Enum`, only `IntEnum`.

```
from enum import Enum, IntEnum
from typing import List

class E(IntEnum):
  A = 1

for e0 in E: print(e0) # Works fine.

#e1:E
for i, e1 in enumerate(E): print(i, e1)
```

```
error: Need type annotation for 'e1'
error: Cannot determine type of 'e1'
```

When the type annotation for e1 is uncommented, I then get `error: <nothing> has no attribute "name"`.


setup.cfg:
```
[mypy]
python_version = 3.6
cache_dir = _build/mypy_cache
mypy_path = ~/work/pithy:./lambda
check_untyped_defs = True
disallow_subclassing_any = True
disallow_untyped_calls = True
disallow_untyped_defs = False
ignore_missing_imports = False
show_column_numbers = True
show_none_errors = True
strict_boolean = False
strict_optional = True
warn_incomplete_stub = True
warn_no_return = True
warn_redundant_casts = True
warn_return_any = True
warn_unused_configs = True
warn_unused_ignores = True
```


Discussion:

Resolving patch:
diff --git a/mypy/constraints.py b/mypy/constraints.py
--- a/mypy/constraints.py
+++ b/mypy/constraints.py
@@ -308,6 +308,8 @@ def visit_instance(self, template: Instance) -> List[Constraint]:
         res = []  # type: List[Constraint]
         if isinstance(actual, CallableType) and actual.fallback is not None:
             actual = actual.fallback
+        if isinstance(actual, Overloaded) and actual.fallback is not None:
+            actual = actual.fallback
         if isinstance(actual, TypedDictType):
             actual = actual.as_anonymous().fallback
         if isinstance(actual, Instance):


Test patch:
diff --git a/test-data/unit/pythoneval.test b/test-data/unit/pythoneval.test
--- a/test-data/unit/pythoneval.test
+++ b/test-data/unit/pythoneval.test
@@ -1243,6 +1243,9 @@ def g(ii: Iterable[int]):
     pass
 f(N)
 g(N)
+reveal_type(list(N))
+[out]
+_testIntEnumIterable.py:11: error: Revealed type is 'builtins.list[_testIntEnumIterable.N*]'
 
 [case testDerivedEnumIterable]
 from enum import Enum
Repository: python/mypy

Issue:
Any base class should not match None
Consider this (oversimplified) code:
```python
from typing import Any

dynamic: Any

class C(dynamic): ...

y: None = C()
```
It passes mypy without errors, but it arguably should not, because `None` is a _non-subclassable_ singleton.

In reality, this causes the following problem: descriptors need to distinguish between access on classes and access on instances, in the former case the instance is `None`. Mypy works well with this pattern that allows to correctly type various ORM patterns. However, if a class has `Any` fallback, then the class and instance access are confused causing weird bugs.


Discussion:

Resolving patch:
diff --git a/mypy/subtypes.py b/mypy/subtypes.py
--- a/mypy/subtypes.py
+++ b/mypy/subtypes.py
@@ -141,6 +141,12 @@ def visit_deleted_type(self, left: DeletedType) -> bool:
 
     def visit_instance(self, left: Instance) -> bool:
         if left.type.fallback_to_any:
+            if isinstance(self.right, NoneTyp):
+                # NOTE: `None` is a *non-subclassable* singleton, therefore no class
+                # can by a subtype of it, even with an `Any` fallback.
+                # This special case is needed to treat descriptors in classes with
+                # dynamic base classes correctly, see #5456.
+                return False
             return True
         right = self.right
         if isinstance(right, TupleType) and right.fallback.type.is_enum:


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
@@ -4549,3 +4549,35 @@ reveal_type(x)  # E: Revealed type is 'builtins.list[__main__.B*[Any]]'
 A = B
 [builtins fixtures/list.pyi]
 [out]
+
+[case testNoneAnyFallback]
+from typing import Any
+dynamic: Any
+class C(dynamic): pass
+x: None = C()  # E: Incompatible types in assignment (expression has type "C", variable has type "None")
+[out]
+
+[case testNoneAnyFallbackDescriptor]
+from typing import Any
+from d import Descr
+
+dynamic: Any
+class C(dynamic):
+    id = Descr(int)
+    name = Descr(str)
+
+c: C
+reveal_type(c.id)  # E: Revealed type is 'builtins.int*'
+reveal_type(C.name)  # E: Revealed type is 'd.Descr[builtins.str*]'
+
+[file d.pyi]
+from typing import Any, overload, Generic, TypeVar, Type
+
+T = TypeVar('T')
+class Descr(Generic[T]):
+    def __init__(self, tp: Type[T]) -> None: ...
+    @overload
+    def __get__(self, inst: None, owner: Any) -> Descr[T]: ...
+    @overload
+    def __get__(self, inst: object, owner: Any) -> T: ...
+[out]
Repository: python/mypy

Issue:
Mypy does not seem to understand custom properties after the descriptor refactor
Consider the following program:

```python
class classproperty:
    def __init__(self, getter):
        self.getter = getter

    def __get__(self, instance, instance_type):
        return self.getter(instance_type)

class Foo:
    @classproperty
    def foo(cls) -> str:
        return "something"

reveal_type(Foo.foo)
print(Foo.foo)
```

If we run mypy on this program, we incorrectly reveal a type of `classproperty` -- but the actual runtime type is `str`.

After doing a git bisect, it looks like this regression was introduced by https://github.com/python/mypy/commit/f47bc236a089b12790334d01eb2f42469f1b530a, if that helps?


Discussion:

Resolving patch:
diff --git a/mypy/checkmember.py b/mypy/checkmember.py
--- a/mypy/checkmember.py
+++ b/mypy/checkmember.py
@@ -549,7 +549,7 @@ def analyze_class_attribute_access(itype: Instance,
         is_classmethod = ((is_decorated and cast(Decorator, node.node).func.is_class)
                           or (isinstance(node.node, FuncBase) and node.node.is_class))
         result = add_class_tvars(t, itype, is_classmethod, builtin_type, original_type)
-        if not (is_lvalue or is_method):
+        if not is_lvalue:
             result = analyze_descriptor_access(original_type, result, builtin_type,
                                                msg, context, chk=chk)
         return result


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
@@ -4616,3 +4616,23 @@ class Descr(Generic[T]):
     @overload
     def __get__(self, inst: object, owner: Any) -> T: ...
 [out]
+
+[case testClassCustomPropertyWorks]
+from typing import TypeVar, Generic, Callable, Any
+
+V = TypeVar('V')
+
+class classproperty(Generic[V]):
+    def __init__(self, getter: Callable[[Any], V]) -> None:
+        self.getter = getter
+    def __get__(self, instance: Any, owner: Any) -> V:
+        return self.getter(owner)
+
+class C:
+    @classproperty
+    def foo(cls) -> int:
+        return 42
+
+reveal_type(C.foo)  # E: Revealed type is 'builtins.int*'
+reveal_type(C().foo)  # E: Revealed type is 'builtins.int*'
+[out]
Repository: python/mypy

Issue:
Daemon should not strip anything that was never analyzed
Consider this test case:
```
[case testIfMypyClass]
from a import x

MYPY = False
if MYPY:
    pass
else:
    class A:
        pass
y: int = x
[file a.py]
x = 1
[file a.py.2]
x = 2
[out]
==
```
It crashes with a traceback ending in
```
/Users/ilevkivskyi/src/mypy/mypy/server/aststrip.py:88: in visit_class_def
    self.strip_type_info(node.info)
/Users/ilevkivskyi/src/mypy/mypy/server/aststrip.py:101: in strip_type_info
    info.add_type_vars()
/Users/ilevkivskyi/src/mypy/mypy/nodes.py:2452: in __getattribute__
    raise AssertionError(object.__getattribute__(self, 'msg'))
AssertionError: ClassDef is lacking info
```
The cause is quite obvious (see topic). The danger here is that there are probably other similar crashes with other non-trivial constructs in unreachable branches, so I think this is high priority. Also this already causes problems in some internal codebases.

@msullivan this is actually a _positive_ effect of a change you made recently, it is better to see this rather than `NoneType has no blah-blah`.


Discussion:
If no-one will start working on this until tomorrow morning, I will submit a fix.

Resolving patch:
diff --git a/mypy/server/aststrip.py b/mypy/server/aststrip.py
--- a/mypy/server/aststrip.py
+++ b/mypy/server/aststrip.py
@@ -44,7 +44,7 @@
     Node, FuncDef, NameExpr, MemberExpr, RefExpr, MypyFile, FuncItem, ClassDef, AssignmentStmt,
     ImportFrom, Import, TypeInfo, SymbolTable, Var, CallExpr, Decorator, OverloadedFuncDef,
     SuperExpr, UNBOUND_IMPORTED, GDEF, MDEF, IndexExpr, SymbolTableNode, ImportAll, TupleExpr,
-    ListExpr, ForStmt
+    ListExpr, ForStmt, Block
 )
 from mypy.semanal_shared import create_indirect_imported_name
 from mypy.traverser import TraverserVisitor
@@ -83,6 +83,11 @@ def strip_file_top_level(self, file_node: MypyFile) -> None:
         self.recurse_into_functions = False
         file_node.accept(self)
 
+    def visit_block(self, b: Block) -> None:
+        if b.is_unreachable:
+            return
+        super().visit_block(b)
+
     def visit_class_def(self, node: ClassDef) -> None:
         """Strip class body and type info, but don't strip methods."""
         self.strip_type_info(node.info)


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
@@ -7530,3 +7530,44 @@ x = 1
 Func = Callable[..., Any]
 [out]
 ==
+
+[case testIfMypyUnreachableClass]
+from a import x
+
+MYPY = False
+if MYPY:
+    pass
+else:
+    class A:
+        pass
+y: int = x
+[file a.py]
+x = 1
+[file a.py.2]
+x = 2
+[builtins fixtures/bool.pyi]
+[out]
+==
+
+[case testIfTypeCheckingUnreachableClass]
+from a import x
+from typing import TYPE_CHECKING
+
+if not TYPE_CHECKING:
+    class A(int):
+        pass
+else:
+    A = int
+
+y: A = x
+[file a.py]
+x = 1
+[file a.py.2]
+x = 2
+[file a.py.3]
+x = 'no way'
+[builtins fixtures/bool.pyi]
+[out]
+==
+==
+main:10: error: Incompatible types in assignment (expression has type "str", variable has type "int")
Repository: python/mypy

Issue:
Regression caused by #5565
#5565 causes the following code to fail with `Name 'x' already defined`, while it is perfectly valid:
```python
class C:
    def __init__(self, x: int) -> None:
        self.x = x
    @property
    def x(self) -> int: ...
    @x.setter
    def x(self, x: int) -> None: ...
```


Discussion:

Resolving patch:
diff --git a/mypy/semanal.py b/mypy/semanal.py
--- a/mypy/semanal.py
+++ b/mypy/semanal.py
@@ -3293,7 +3293,7 @@ def add_symbol(self, name: str, node: SymbolTableNode,
             self.locals[-1][name] = node
         elif self.type:
             existing = self.type.names.get(name)
-            if existing and existing.node != node.node:
+            if existing and isinstance(existing.node, TypeInfo) and existing.node != node.node:
                 self.name_already_defined(name, context, existing)
                 return
             self.type.names[name] = node


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
@@ -5087,3 +5087,33 @@ c = D()
 from a import Other
 class B: ...
 [out]
+
+[case testAllowPropertyAndInit1]
+class C:
+    def __init__(self, x: int) -> None:
+        self.x = x
+    @property
+    def x(self) -> int: pass
+    @x.setter
+    def x(self, x: int) -> None: pass
+[builtins fixtures/property.pyi]
+[out]
+
+[case testAllowPropertyAndInit2]
+class C:
+    @property
+    def x(self) -> int: pass
+    @x.setter
+    def x(self, x: int) -> None: pass
+    def __init__(self, x: int) -> None:
+        self.x = x
+[builtins fixtures/property.pyi]
+
+[case testAllowPropertyAndInit3]
+class C:
+    def __init__(self, x: int) -> None:
+        self.x = x  # type: ignore
+    @property  # Should be no error here
+    def x(self) -> int: pass
+[builtins fixtures/property.pyi]
+[out]
Repository: python/mypy

Issue:
Can't assign to ()
Mypy incorrectly complains about assignments to `()`. The simplest example of this is
```python
() = []
```
This code executes without a problem, but mypy says `error: can't assign to ()`

A more real world use case might be code like this
```python
(a, b), () = [[1, 2], []]
```
In this case the assignment to `()` is a concise way of asserting that the second list is empty.

* What is the actual behavior/output?
`error: can't assign to ()`
* What is the behavior/output you expect?
No type checking errors
* What are the versions of mypy and Python you are using?
A build from the latest commit as of writing this, 614090b7
* What are the mypy flags you are using?
No flags

If this is a change you decide would be good then I believe it could be implemented by removing the  the check on line 1930 of `mypy/semanal.py` and updating the tests.



Discussion:
Thanks for the report! This seems like a real bug, but low-priority because little real-world code would do it. If somebody submits a PR to fix it, we'll take a look.

Resolving patch:
diff --git a/mypy/semanal.py b/mypy/semanal.py
--- a/mypy/semanal.py
+++ b/mypy/semanal.py
@@ -2636,9 +2636,6 @@ def analyze_lvalue(self,
                 self.fail('Unexpected type declaration', lval)
             lval.accept(self)
         elif isinstance(lval, TupleExpr):
-            items = lval.items
-            if len(items) == 0 and isinstance(lval, TupleExpr):
-                self.fail("can't assign to ()", lval)
             self.analyze_tuple_or_list_lvalue(lval, explicit_type)
         elif isinstance(lval, StarExpr):
             if nested:


Test patch:
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
@@ -1458,3 +1458,15 @@ x7, x8, y7, y8 = *points2, *points3 # E: Contiguous iterable with same type expe
 
 x9, y9, x10, y10, z5 = *points2, 1, *points2 # E: Contiguous iterable with same type expected
 [builtins fixtures/tuple.pyi]
+
+[case testAssignEmptyPy36]
+# flags: --python-version 3.6
+() = []
+
+[case testAssignEmptyPy27]
+# flags: --python-version 2.7
+() = []  # E: can't assign to ()
+
+[case testAssignEmptyBogus]
+() = 1  # E: 'Literal[1]?' object is not iterable
+[builtins fixtures/tuple.pyi]
diff --git a/test-data/unit/semanal-errors.test b/test-data/unit/semanal-errors.test
--- a/test-data/unit/semanal-errors.test
+++ b/test-data/unit/semanal-errors.test
@@ -377,11 +377,6 @@ main:1: error: can't assign to literal
 [out]
 main:1: error: can't assign to literal
 
-[case testInvalidLvalues5]
-() = 1
-[out]
-main:1: error: can't assign to ()
-
 [case testInvalidLvalues6]
 x = y = z = 1  # ok
 x, (y, 1) = 1