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

Issue:
join_types(UninhabitedType, t) should be t
For some reason `join_simple` has logic to move `UninhabitedType` to the second argument but `join_types` does not.



Discussion:
I'm not sure why we haven't seen this cause any issues, but this definitely seems like a bug.  Should be straightforward to fix.

It came up in #1748 when type checking an expression like `a if False else b`. I changed that test to better reflect its original intent but after #1748 we'll have the wrong inferred type for that (admittedly unlikely) expression.

I forget why we have two `join_*` functions in the first place, though...


Resolving patch:
diff --git a/mypy/join.py b/mypy/join.py
--- a/mypy/join.py
+++ b/mypy/join.py
@@ -82,6 +82,9 @@ def join_types(s: Type, t: Type) -> Type:
     if isinstance(s, NoneTyp) and not isinstance(t, NoneTyp):
         s, t = t, s
 
+    if isinstance(s, UninhabitedType) and not isinstance(t, UninhabitedType):
+        s, t = t, s
+
     # Use a visitor to handle non-trivial cases.
     return t.accept(TypeJoinVisitor(s))
 


Test patch:
Repository: python/mypy

Issue:
--warn-no-return Warns about functions that have no return statements if used in tandem with --strict-optional
UPDATED - This problem appears to happen when `--warn-no-return` is used in tandem with `--strict-optional`

test.py:

``` python
class Foo():
    def __init__(self) -> None:
        self.x = 0
    def increment_x(self) -> None:
        self.x += 1
```

`mypy -s --fast-parser --warn-no-return --strict-optional test.py`

```
test.py: note: In member "__init__" of class "Foo":
test.py:2: note: Missing return statement
test.py: note: In member "increment_x" of class "Foo":
test.py:4: note: Missing return statement
```



Discussion:
This is just a bug caused by the fact that `--strict-optional` changes the meaning of returning `None` internally in mypy. It works fine without `--strict-optional`.

Got it.  Thanks @rwbarton for figuring out what I meant even though I forgot to specify what my flags were.  Changed the title to reflect the actual problem.

So really this is just a problematic interaction between --warn-no-return and --strict-optional.


Resolving patch:
diff --git a/mypy/checker.py b/mypy/checker.py
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -634,7 +634,7 @@ def is_implicit_any(t: Type) -> bool:
                 unreachable = self.binder.is_unreachable()
 
             if (self.options.warn_no_return and not unreachable
-                    and not isinstance(self.return_types[-1], (Void, AnyType))
+                    and not isinstance(self.return_types[-1], (Void, NoneTyp, AnyType))
                     and not defn.is_generator):
                 # Control flow fell off the end of a function that was
                 # declared to return a non-None type.


Test patch:
diff --git a/test-data/unit/check-optional.test b/test-data/unit/check-optional.test
--- a/test-data/unit/check-optional.test
+++ b/test-data/unit/check-optional.test
@@ -497,3 +497,15 @@ if x == y:
 else:
     reveal_type(x)  # E: Revealed type is 'Union[builtins.str, builtins.int, builtins.None]'
 [builtins fixtures/ops.pyi]
+
+
+[case testWarnNoReturnWorksWithStrictOptional]
+# flags: --warn-no-return
+def f() -> None:
+  1 + 1  # no error
+
+def g() -> int:
+  1 + 1  #
+[out]
+main: note: In function "g":
+main:5: note: Missing return statement
Repository: python/mypy

Issue:
Self-type doesn't seem to work for properties
I found this when trying to use self-type for pathlib (see PR python/typeshed#658). There are a few properties that have type PurePath and are repeated in the Path subclass. The stub uses plain attributes for these, but the implementation has properties, so I want to replace them with properties. However this doesn't seem to work. In particular I'm trying to add this to class PurePath:
```
    @property
    def parents(self: _P) -> Sequence[_P]: ...
    @property
    def parent(self: _P) -> _P: ...
```
Now I have an example class:
```
class MyPath(pathlib.PosixPath):
    def parity(self):
        return len(str(self)) % 2

root = MyPath('/')
reveal_type(root.parent)

```
This reveals MyPath as the type but *also* gives an error:
```
__tmp__.py:14: error: Revealed type is '__tmp__.MyPath*'
__tmp__.py:14: error: Invalid method type
```
If I remove the self-type, e.g.
```
    @property
    def parents(self) -> Sequence[PurePath]: ...
    @property
    def parent(self) -> PurePath: ...
```
the error goes away but the revealed type reverts back to (of course) PurePath.

@elazarg thoughts?


Discussion:
@gvanrossum I'm thinking you were intending to @ mention someone else. 😉 It would be my luck that, the one time I'm contacted by the creator of Python, it's by mistake.

Yup, sorry for that. :-/


Resolving patch:
diff --git a/mypy/checkmember.py b/mypy/checkmember.py
--- a/mypy/checkmember.py
+++ b/mypy/checkmember.py
@@ -323,7 +323,7 @@ def check_method_type(functype: FunctionLike, itype: Instance, is_classmethod: b
             # we passed to typ.fallback in analyze_member_access. See #1432.
             if isinstance(selfarg, TupleType):
                 selfarg = selfarg.fallback
-            if not subtypes.is_equivalent(selfarg, itype):
+            if not subtypes.is_subtype(selfarg, itype):
                 msg.invalid_method_type(item, context)
         else:
             # Check that cls argument has type 'Any' or valid class type.


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
@@ -333,3 +333,21 @@ class E:
     def __new__(cls) -> E:
         reveal_type(cls)  # E: Revealed type is 'def () -> __main__.E'
         return cls()
+
+[case testSelfTypeProperty]
+from typing import TypeVar
+
+T = TypeVar('T', bound='A')
+
+class A:
+    @property
+    def member(self: T) -> T:
+        pass
+
+class B(A):
+    pass
+
+reveal_type(A().member)  # E: Revealed type is '__main__.A*'
+reveal_type(B().member)  # E: Revealed type is '__main__.B*'
+
+[builtins fixtures/property.pyi]
Repository: python/mypy

Issue:
Enum of a NamedTuple-derived type leads to incompatible type error
This code:

``` python
from typing import NamedTuple
from enum import Enum

Foo = NamedTuple('Foo', [('bar', int)])

class MyEnum(Foo, Enum):
    CONSTANT = Foo(bar=1)

def f(x):
    # type: (MyEnum) -> None
    pass

f(MyEnum.CONSTANT)
```

leads to:

```
error: Argument 1 to "f" has incompatible type "test.MyEnum"; expected "MyEnum"
```



Discussion:
I know we have plenty of namedtuple-related issues. But does this code serve a real purpose? Enum has a lot of magic, so does namedtuple -- I'm not sure if we should really be required to make sense of this, and what you're trying to accomplishing with that class.

This is a distilled example of a real-life enum I came across in our code. Not going to get into whether or not having such an enum is a good idea, but we have it and I'm getting mypy errors trying to use it as an argument to a function. The main weirdness is that the error is of the form `incompatible type: "fully.qualified.path.to.MyEnum"; expected "MyEnum"` which seems fishy.

Note that without the Foo base class you can still access the bar attribute in f() -- use x.value.bar rather than x.bar.

This came up again today -- a user hit an error message just as confusing (and with the same structure) as the one in @alexsydell's report, and after some debugging someone else recognized it as this issue.

In addition to the type-checker issue that we shouldn't be reporting an error here at all, the error message is awfully perplexing and is likely an example of #1582.

I believe that this is a result of the special casing of both `Enum` and `NamedTuple`. It can be special-cased too at [subtypes.py](https://github.com/python/mypy/blob/master/mypy/subtypes.py#L122-L123):

```
        right = self.right
+       if isinstance(right, TupleType) and right.fallback.type.is_enum:
+           return is_subtype(left, right.fallback)
        if isinstance(right, Instance):
```

I think that this special casing is justified, but I'm not sure.


Resolving patch:
diff --git a/mypy/subtypes.py b/mypy/subtypes.py
--- a/mypy/subtypes.py
+++ b/mypy/subtypes.py
@@ -120,6 +120,8 @@ def visit_instance(self, left: Instance) -> bool:
         if left.type.fallback_to_any:
             return True
         right = self.right
+        if isinstance(right, TupleType) and right.fallback.type.is_enum:
+            return is_subtype(left, right.fallback)
         if isinstance(right, Instance):
             if left.type._promote and is_subtype(left.type._promote,
                                                  self.right,


Test patch:
diff --git a/test-data/unit/pythoneval-enum.test b/test-data/unit/pythoneval-enum.test
--- a/test-data/unit/pythoneval-enum.test
+++ b/test-data/unit/pythoneval-enum.test
@@ -118,3 +118,17 @@ takes_int(SomeExtIntEnum.x)
 def takes_some_ext_int_enum(s: SomeExtIntEnum):
     pass
 takes_some_ext_int_enum(SomeExtIntEnum.x)
+
+
+[case testNamedTupleEnum]
+from typing import NamedTuple
+from enum import Enum
+
+N = NamedTuple('N', [('bar', int)])
+
+class E(N, Enum):
+    X = N(1)
+
+def f(x: E) -> None: pass
+
+f(E.X)
Repository: python/mypy

Issue:
Type application of generic function shouldn't be allowed
mypy accepts this program, which will fail at runtime:

``` py
from typing import TypeVar
T = TypeVar('T')
def f(x: T) -> T: pass
y = f[int]
```

(It's a holdover from the old language which did allow this kind of instantiation of generic functions.)



Discussion:

Resolving patch:
diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py
--- a/mypy/checkexpr.py
+++ b/mypy/checkexpr.py
@@ -1361,12 +1361,16 @@ def visit_type_application(self, tapp: TypeApplication) -> Type:
         """Type check a type application (expr[type, ...])."""
         tp = self.accept(tapp.expr)
         if isinstance(tp, CallableType):
+            if not tp.is_type_obj():
+                self.chk.fail(messages.ONLY_CLASS_APPLICATION, tapp)
             if len(tp.variables) != len(tapp.types):
                 self.msg.incompatible_type_application(len(tp.variables),
                                                        len(tapp.types), tapp)
                 return AnyType()
             return self.apply_generic_arguments(tp, tapp.types, tapp)
         elif isinstance(tp, Overloaded):
+            if not tp.is_type_obj():
+                self.chk.fail(messages.ONLY_CLASS_APPLICATION, tapp)
             for item in tp.items():
                 if len(item.variables) != len(tapp.types):
                     self.msg.incompatible_type_application(len(item.variables),
diff --git a/mypy/messages.py b/mypy/messages.py
--- a/mypy/messages.py
+++ b/mypy/messages.py
@@ -66,6 +66,7 @@
 FUNCTION_PARAMETER_CANNOT_BE_COVARIANT = "Cannot use a covariant type variable as a parameter"
 INCOMPATIBLE_IMPORT_OF = "Incompatible import of"
 FUNCTION_TYPE_EXPECTED = "Function is missing a type annotation"
+ONLY_CLASS_APPLICATION = "Type application is only supported for generic classes"
 RETURN_TYPE_EXPECTED = "Function is missing a return type annotation"
 ARGUMENT_TYPE_EXPECTED = "Function is missing a type annotation for one or more arguments"
 KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE = \


Test patch:
diff --git a/test-data/unit/check-generics.test b/test-data/unit/check-generics.test
--- a/test-data/unit/check-generics.test
+++ b/test-data/unit/check-generics.test
@@ -417,6 +417,14 @@ class A(Generic[T]):
 [out]
 main: note: In member "f" of class "A":
 
+[case testProhibitTypeApplicationToGenericFunctions]
+from typing import TypeVar
+T = TypeVar('T')
+def f(x: T) -> T: pass
+
+y = f[int]  # E: Type application is only supported for generic classes
+[out]
+
 
 -- Generic types in expressions
 -- ----------------------------
Repository: python/mypy

Issue:
type of Union containing Any is incorrectly inferred after an isinstance check
`union_any.py`:

``` py
from typing import Any, Union

def func(v):
    # type: (Union[int, Any]) -> str
    if isinstance(v, int):
        s = hex(v)
    else:
        s = str(v).lower()
    return "key:" + s
```

`mypy union_any.py`:

```
union_any.py: note: In function "func":
union_any.py:8: error: No overload variant of "str" matches argument types [Union[<ERROR>, void]]
```

`mypy --py2 union_any.py`:

```
union_any.py: note: In function "func":
union_any.py:8: error: Argument 1 to "str" has incompatible type "Union[object, None]"; expected "object"
```

I discovered this when I used a class which was defined in some library which did not have stubs and I was using `--silent-imports`.



Discussion:
In addition to being a Union[Any, ...] -> Any problem, I think this is at least vaguely related to #1691.

Another case where I found this error is when 2 classes inherit from `Any`:

`file1.py`:

``` py
from typing import Any, Union

class B(Any): name = 'Bob'
class C(Any): name = 'Charlie'

def func(x):
    # type: (Union[B, C]) -> None
    reveal_type(x)
    if isinstance(x, B):
        reveal_type(x)
        print(x.name)
    else:
        reveal_type(x)
        print(x.name)
```

gives this output:

```
file1.py: note: In function "func":
file1.py:8: error: Revealed type is 'Union[file1.B, file1.C]'
file1.py:10: error: Revealed type is 'file1.B'
file1.py:13: error: Revealed type is 'Union[<ERROR>, <ERROR>]'
file1.py:14: error: Some element of union has no attribute "name"
```

It works fine when I replace `Any` by `object`.

On that second case: inheriting from Any is illegal (though it can happen legally when you inherit from a class whose import is suppressed by `--silent-imports`).


Resolving patch:
diff --git a/mypy/subtypes.py b/mypy/subtypes.py
--- a/mypy/subtypes.py
+++ b/mypy/subtypes.py
@@ -345,7 +345,8 @@ def restrict_subtype_away(t: Type, s: Type) -> Type:
     Currently just remove elements of a union type.
     """
     if isinstance(t, UnionType):
-        new_items = [item for item in t.items if not is_subtype(item, s)]
+        new_items = [item for item in t.items if (not is_subtype(item, s)
+                                                  or isinstance(item, AnyType))]
         return UnionType.make_union(new_items)
     else:
         return t


Test patch:
diff --git a/test-data/unit/check-unions.test b/test-data/unit/check-unions.test
--- a/test-data/unit/check-unions.test
+++ b/test-data/unit/check-unions.test
@@ -35,6 +35,17 @@ def f(x: Union[int, str]) -> None:
 [out]
 main: note: In function "f":
 
+[case testUnionAnyIsInstance]
+from typing import Any, Union
+
+def func(v:Union[int, Any]) -> None:
+    if isinstance(v, int):
+        reveal_type(v) # E: Revealed type is 'builtins.int'
+    else:
+        reveal_type(v) # E: Revealed type is 'Any'
+[builtins fixtures/isinstance.pyi]
+[out]
+main: note: In function "func":
 
 [case testUnionAttributeAccess]
 from typing import Union
Repository: python/mypy

Issue:
Crash in fastparse2.py on print statement with trailing comma
Repro (run `mypy -2 --fast-parser`):
```python
print 0,
```
Last lines of the traceback:
```
  File "/Users/guido/v3/lib/python3.6/site-packages/mypy/fastparse2.py", line 541, in visit_Print
    keywords.append(ast27.keyword("end", ast27.Str(" ", lineno=n.lineno, col_offset=-1)))
TypeError: Str constructor takes either 0 or 2 positional arguments
```


Discussion:

Resolving patch:
diff --git a/mypy/fastparse2.py b/mypy/fastparse2.py
--- a/mypy/fastparse2.py
+++ b/mypy/fastparse2.py
@@ -543,7 +543,8 @@ def visit_Print(self, n: ast27.Print) -> ExpressionStmt:
             keywords.append(ast27.keyword("file", n.dest))
 
         if not n.nl:
-            keywords.append(ast27.keyword("end", ast27.Str(" ", lineno=n.lineno, col_offset=-1)))
+            keywords.append(ast27.keyword("end", ast27.Str(" ", 0,
+                                                           lineno=n.lineno, col_offset=-1)))
 
         # TODO: Rather then desugaring Print into an intermediary ast27.Call object, it might
         # be more efficient to just directly create a mypy.node.CallExpr object.


Test patch:
diff --git a/test-data/unit/check-fastparse.test b/test-data/unit/check-fastparse.test
--- a/test-data/unit/check-fastparse.test
+++ b/test-data/unit/check-fastparse.test
@@ -189,3 +189,8 @@ from typing import Dict
 x = None # type: Dict[x: y]
 [out]
 main:3: error: syntax error in type comment
+
+[case testPrintStatementTrailingCommaFastParser_python2]
+# flags: --fast-parser
+print 0,
+print 1, 2,
Repository: python/mypy

Issue:
Add --hide-error-context back (undocumented)
See PR #2540. This replaced --hide-error-context with --show-error-context (and changed the default). But for backwards compatibility and in case one wants to override the config file with a manual flag it would be nice to add
```python
parser.add_argument('--hide-error-context', action='store_true',
                        dest='hide_error_context',
                        help=argparse.SUPPRESS)
```


Discussion:
While you're at it maybe move the hide_error_context option out of the experimental section in options.py?

Resolving patch:
diff --git a/mypy/main.py b/mypy/main.py
--- a/mypy/main.py
+++ b/mypy/main.py
@@ -222,6 +222,9 @@ def process_options(args: List[str],
     # which will make the cache writing process output pretty-printed JSON (which
     # is easier to debug).
     parser.add_argument('--debug-cache', action='store_true', help=argparse.SUPPRESS)
+    parser.add_argument('--hide-error-context', action='store_true',
+                        dest='hide_error_context',
+                        help=argparse.SUPPRESS)
     # deprecated options
     parser.add_argument('-f', '--dirty-stubs', action='store_true',
                         dest='special-opts:dirty_stubs',
diff --git a/mypy/options.py b/mypy/options.py
--- a/mypy/options.py
+++ b/mypy/options.py
@@ -73,6 +73,9 @@ def __init__(self) -> None:
         # Apply strict None checking
         self.strict_optional = False
 
+        # Hide "note: In function "foo":" messages.
+        self.hide_error_context = True
+
         # Files in which to allow strict-Optional related errors
         # TODO: Kill this in favor of show_none_errors
         self.strict_optional_whitelist = None   # type: Optional[List[str]]
@@ -111,7 +114,6 @@ def __init__(self) -> None:
         self.incremental = False
         self.cache_dir = defaults.CACHE_DIR
         self.debug_cache = False
-        self.hide_error_context = True  # Hide "note: In function "foo":" messages.
         self.shadow_file = None  # type: Optional[Tuple[str, str]]
         self.show_column_numbers = False  # type: bool
 


Test patch:
Repository: python/mypy

Issue:
Sometimes incremental believes an entire SCC must be re-processed despite no changes
While running misc/incremental_checker.py on our internal codebase "C" I discovered that even with a warm cache and no changed files, incremental mode decides to reprocess about half the files. In particular we have a large cycle (SCC) that is being reprocessed in its entirety. This greatly reduces the effectiveness of incremental mode (it only save 50% of the time in the best case).

In contrast, in our "S" codebase this phenomenon does not occur -- a full run takes 5 minutes while a no-changes run with warm cache completes in 7 seconds (presumably the time it takes to stat and read all 3490 cache metadata files only).


Discussion:
This seems to be happening because there are some files whose per-file option value differs from the global default. The check for matching options at the end of find_cache_meta() doesn't take per-file options into account.

Resolving patch:
diff --git a/mypy/build.py b/mypy/build.py
--- a/mypy/build.py
+++ b/mypy/build.py
@@ -783,7 +783,7 @@ def find_cache_meta(id: str, path: str, manager: BuildManager) -> Optional[Cache
 
     # Ignore cache if (relevant) options aren't the same.
     cached_options = m.options
-    current_options = manager.options.select_options_affecting_cache()
+    current_options = manager.options.clone_for_module(id).select_options_affecting_cache()
     if cached_options != current_options:
         manager.trace('Metadata abandoned for {}: options differ'.format(id))
         return None


Test patch:
diff --git a/test-data/unit/check-incremental.test b/test-data/unit/check-incremental.test
--- a/test-data/unit/check-incremental.test
+++ b/test-data/unit/check-incremental.test
@@ -1766,3 +1766,15 @@ main:4: error: Revealed type is 'def () -> ntcrash.C.A@4'
 main:2: error: Revealed type is 'TypedDict(x=builtins.int, _fallback=typing.Mapping[builtins.str, builtins.int])'
 main:3: error: Revealed type is 'TypedDict(x=builtins.int, _fallback=ntcrash.C.A@4)'
 main:4: error: Revealed type is 'def () -> ntcrash.C.A@4'
+
+[case testIncrementalPerFileFlags]
+# flags: --config-file tmp/mypy.ini
+import a
+[file a.py]
+pass
+[file mypy.ini]
+[[mypy]
+warn_no_return = False
+[[mypy-a]
+warn_no_return = True
+[rechecked]
Repository: python/mypy

Issue:
`Tuple[()]` is occasionally converted to `Tuple[Any, ...]`
Most obvious when the `Tuple[()]` is passed through a Callable
```
from typing import *

Type = Callable[[Tuple[()]], int]
x = "foo" # type: Type
```
Results in:
```
Incompatible types in assignment (expression has type "str", variable has type Callable[[Tuple[Any, ...]], int])
```

As a side note,
```Type = Tuple[()]```
Also appears to give a weird error.


Discussion:

Resolving patch:
diff --git a/mypy/exprtotype.py b/mypy/exprtotype.py
--- a/mypy/exprtotype.py
+++ b/mypy/exprtotype.py
@@ -37,6 +37,8 @@ def expr_to_unanalyzed_type(expr: Expression) -> Type:
             else:
                 args = [expr.index]
             base.args = [expr_to_unanalyzed_type(arg) for arg in args]
+            if not base.args:
+                base.empty_tuple_index = True
             return base
         else:
             raise TypeTranslationError()


Test patch:
diff --git a/test-data/unit/check-type-aliases.test b/test-data/unit/check-type-aliases.test
--- a/test-data/unit/check-type-aliases.test
+++ b/test-data/unit/check-type-aliases.test
@@ -61,3 +61,14 @@ def f(x: bytes): pass
 bytes
 f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "str"
 [builtins fixtures/alias.pyi]
+
+[case testEmptyTupleTypeAlias]
+from typing import Tuple, Callable
+EmptyTuple = Tuple[()]
+x = None # type: EmptyTuple
+reveal_type(x)  # E: Revealed type is 'Tuple[]'
+
+EmptyTupleCallable = Callable[[Tuple[()]], None]
+f = None # type: EmptyTupleCallable
+reveal_type(f)  # E: Revealed type is 'def (Tuple[])'
+[builtins fixtures/list.pyi]