gurudesh/pytracebugs huggingface dataset:
# Buggy code
def visit_callable_type(self, left: CallableType) -> bool:
    right = self.right
    if isinstance(right, CallableType):
        return is_callable_compatible(
            left,
            right,
            is_compat=self._is_subtype,
            ignore_pos_arg_names=self.ignore_pos_arg_names,
        )
    elif isinstance(right, Overloaded):
        return all(self._is_subtype(left, item) for item in right.items())
    elif isinstance(right, Instance):
        if right.type.is_protocol and right.type.protocol_members == ["__call__"]:
            # OK, a callable can implement a protocol with a single `__call__` member.
            # TODO: we should probably explicitly exclude self-types in this case.
            call = find_member("__call__", right, left)
            assert call is not None
            if self._is_subtype(left, call):
                return True
        return self._is_subtype(left.fallback, right)
    elif isinstance(right, TypeType):
        # This is unsound, we don't check the __init__ signature.
        return left.is_type_obj() and self._is_subtype(left.ret_type, right.item)
    else:
        return False


# Traceback (RecursionError)
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb

# Fixed code
def visit_callable_type(self, left: CallableType) -> bool:
    right = self.right
    if isinstance(right, CallableType):
        return is_callable_compatible(
            left,
            right,
            is_compat=self._is_subtype,
            ignore_pos_arg_names=self.ignore_pos_arg_names,
        )
    elif isinstance(right, Overloaded):
        return all(self._is_subtype(left, item) for item in right.items())
    elif isinstance(right, Instance):
        if right.type.is_protocol and right.type.protocol_members == ["__call__"]:
            # OK, a callable can implement a protocol with a single `__call__` member.
            # TODO: we should probably explicitly exclude self-types in this case.
            call = find_member("__call__", right, left, is_operator=True)
            assert call is not None
            if self._is_subtype(left, call):
                return True
        return self._is_subtype(left.fallback, right)
    elif isinstance(right, TypeType):
        # This is unsound, we don't check the __init__ signature.
        return left.is_type_obj() and self._is_subtype(left.ret_type, right.item)
    else:
        return False
# Buggy code
def calculate_class_mro(
    self, defn: ClassDef, obj_type: Optional[Callable[[], Instance]] = None
) -> None:
    """Calculate method resolution order for a class.

    `obj_type` may be omitted in the third pass when all classes are already analyzed.
    It exists just to fill in empty base class list during second pass in case of
    an import cycle.
    """
    try:
        calculate_mro(defn.info, obj_type)
    except MroError:
        self.fail_blocker(
            "Cannot determine consistent method resolution "
            'order (MRO) for "%s"' % defn.name,
            defn,
        )
        defn.info.mro = []
    # Allow plugins to alter the MRO to handle the fact that `def mro()`
    # on metaclasses permits MRO rewriting.
    if defn.fullname:
        hook = self.plugin.get_customize_class_mro_hook(defn.fullname)
        if hook:
            hook(ClassDefContext(defn, Expression(), self))


# Traceback (TypeError)
tmp/sample.py:1: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "ve/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "mypy/semanal.py", line 3791, in accept
File "mypy/nodes.py", line 895, in accept__Node_glue
File "mypy/nodes.py", line 896, in accept
File "mypy/semanal.py", line 804, in visit_class_def__StatementVisitor_glue
File "mypy/semanal.py", line 807, in visit_class_def
File "mypy/semanal.py", line 819, in analyze_class
File "mypy/semanal.py", line 1229, in analyze_base_classes
File "mypy/semanal.py", line 1250, in calculate_class_mro
TypeError: interpreted classes cannot inherit from compiled
tmp/sample.py:1: : note: use --pdb to drop into pdb

# Fixed code
def calculate_class_mro(
    self, defn: ClassDef, obj_type: Optional[Callable[[], Instance]] = None
) -> None:
    """Calculate method resolution order for a class.

    `obj_type` may be omitted in the third pass when all classes are already analyzed.
    It exists just to fill in empty base class list during second pass in case of
    an import cycle.
    """
    try:
        calculate_mro(defn.info, obj_type)
    except MroError:
        self.fail_blocker(
            "Cannot determine consistent method resolution "
            'order (MRO) for "%s"' % defn.name,
            defn,
        )
        defn.info.mro = []
    # Allow plugins to alter the MRO to handle the fact that `def mro()`
    # on metaclasses permits MRO rewriting.
    if defn.fullname:
        hook = self.plugin.get_customize_class_mro_hook(defn.fullname)
        if hook:
            hook(ClassDefContext(defn, FakeExpression(), self))
# Buggy code
def false_only(t: Type) -> Type:
    """
    Restricted version of t with only False-ish values
    """
    if not t.can_be_false:
        # All values of t are True-ish, so there are no false values in it
        return UninhabitedType(line=t.line)
    elif not t.can_be_true:
        # All values of t are already False-ish, so false_only is idempotent in this case
        return t
    elif isinstance(t, UnionType):
        # The false version of a union type is the union of the false versions of its components
        new_items = [false_only(item) for item in t.items]
        return UnionType.make_simplified_union(new_items, line=t.line, column=t.column)
    else:
        new_t = copy_type(t)
        new_t.can_be_true = False
        return new_t


# Traceback (AttributeError)
$ mypy n.py
n.py:11: error: Incompatible types in assignment (expression has type "int", variable has type "str")
$ python3 n.py
Traceback (most recent call last):
File "n.py", line 23, in <module>
Foo()
File "n.py", line 15, in __init__
self.mypy_does_not_typecheck_this()  # no error
AttributeError: 'Foo' object has no attribute 'mypy_does_not_typecheck_this'

# Fixed code
def false_only(t: Type) -> Type:
    """
    Restricted version of t with only False-ish values
    """
    if not t.can_be_false:
        if state.strict_optional:
            # All values of t are True-ish, so there are no false values in it
            return UninhabitedType(line=t.line)
        else:
            # When strict optional checking is disabled, everything can be
            # False-ish since anything can be None
            return NoneType(line=t.line)
    elif not t.can_be_true:
        # All values of t are already False-ish, so false_only is idempotent in this case
        return t
    elif isinstance(t, UnionType):
        # The false version of a union type is the union of the false versions of its components
        new_items = [false_only(item) for item in t.items]
        return UnionType.make_simplified_union(new_items, line=t.line, column=t.column)
    else:
        new_t = copy_type(t)
        new_t.can_be_true = False
        return new_t
# Buggy code
def find_module_path_and_all_py3(
    module: str,
) -> Optional[Tuple[str, Optional[List[str]]]]:
    """Find module and determine __all__ for a Python 3 module.

    Return None if the module is a C module. Return (module_path, __all__) if
    it is a Python module. Raise CantImport if import failed.
    """
    # TODO: Support custom interpreters.
    try:
        mod = importlib.import_module(module)
    except Exception:
        raise CantImport(module)
    if is_c_module(mod):
        return None
    return mod.__file__, getattr(mod, "__all__", None)


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/peter/.local/share/virtualenvs/testpy-XO9km9Nb/bin/stubgen", line 10, in <module>
sys.exit(main())
File "mypy/stubgen.py", line 1191, in main
File "mypy/stubgen.py", line 1075, in generate_stubs
File "mypy/stubgen.py", line 899, in collect_build_targets
File "mypy/stubgen.py", line 930, in find_module_paths_using_imports
TypeError: tuple object expected

# Fixed code
def find_module_path_and_all_py3(
    module: str,
) -> Optional[Tuple[str, Optional[List[str]]]]:
    """Find module and determine __all__ for a Python 3 module.

    Return None if the module is a C module. Return (module_path, __all__) if
    it is a Python module. Raise CantImport if import failed.
    """
    # TODO: Support custom interpreters.
    try:
        mod = importlib.import_module(module)
    except Exception:
        raise CantImport(module)
    if is_c_module(mod):
        return None
    module_all = getattr(mod, "__all__", None)
    if module_all is not None:
        module_all = list(module_all)
    return mod.__file__, module_all
# Buggy code
def _load_json_file(
    file: str, manager: BuildManager, log_sucess: str, log_error: str
) -> Optional[Dict[str, Any]]:
    """A simple helper to read a JSON file with logging."""
    try:
        data = manager.metastore.read(file)
    except IOError:
        manager.log(log_error + file)
        return None
    manager.trace(log_sucess + data.rstrip())
    result = json.loads(data)  # TODO: Errors
    return result


# Traceback (json.decoder.JSONDecodeError)
Traceback (most recent call last):
File "/usr/local/bin/mypy", line 11, in <module>
sys.exit(console_entry())
File "/usr/local/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/usr/local/lib/python3.7/site-packages/mypy/main.py", line 92, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/usr/local/lib/python3.7/site-packages/mypy/build.py", line 156, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/usr/local/lib/python3.7/site-packages/mypy/build.py", line 206, in _build
graph = dispatch(sources, manager)
File "/usr/local/lib/python3.7/site-packages/mypy/build.py", line 2178, in dispatch
graph = load_graph(sources, manager)
File "/usr/local/lib/python3.7/site-packages/mypy/build.py", line 2336, in load_graph
root_source=True)
File "/usr/local/lib/python3.7/site-packages/mypy/build.py", line 1476, in __init__
self.meta = find_cache_meta(self.id, path, manager)
File "/usr/local/lib/python3.7/site-packages/mypy/build.py", line 862, in find_cache_meta
log_error='Could not load cache for {}: '.format(id))
File "/usr/local/lib/python3.7/site-packages/mypy/build.py", line 790, in _load_json_file
result = json.loads(data)  # TODO: Errors
File "/usr/local/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 105 column 5 (char 5143)

# Fixed code
def _load_json_file(
    file: str, manager: BuildManager, log_sucess: str, log_error: str
) -> Optional[Dict[str, Any]]:
    """A simple helper to read a JSON file with logging."""
    try:
        data = manager.metastore.read(file)
    except IOError:
        manager.log(log_error + file)
        return None
    manager.trace(log_sucess + data.rstrip())
    try:
        result = json.loads(data)
    except ValueError:  # TODO: JSONDecodeError in 3.5
        manager.errors.set_file(file, None)
        manager.errors.report(
            -1,
            -1,
            "Error reading JSON file;"
            " you likely have a bad cache.\n"
            "Try removing the {cache_dir} directory"
            " and run mypy again.".format(cache_dir=manager.options.cache_dir),
            blocker=True,
        )
        return None
    else:
        return result
# Buggy code
def __init__(self, items: List["OverloadPart"]) -> None:
    super().__init__()
    assert len(items) > 0
    self.items = items
    self.unanalyzed_items = items.copy()
    self.impl = None
    self.set_line(items[0].line)
    self.is_final = False


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/andrew/.virtualenvs/platform-api-clients/bin/mypy", line 11, in <module>
sys.exit(console_entry())
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/main.py", line 92, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/build.py", line 156, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/build.py", line 206, in _build
graph = dispatch(sources, manager)
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/build.py", line 2232, in dispatch
process_graph(graph, manager)
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/build.py", line 2525, in process_graph
process_fresh_modules(graph, prev_scc, manager)
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/build.py", line 2609, in process_fresh_modules
graph[id].load_tree()
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/build.py", line 1604, in load_tree
self.tree = MypyFile.deserialize(data)
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/nodes.py", line 277, in deserialize
tree.names = SymbolTable.deserialize(data['names'])
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/nodes.py", line 2864, in deserialize
st[key] = SymbolTableNode.deserialize(value)
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/nodes.py", line 2812, in deserialize
node = SymbolNode.deserialize(data['node'])
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/nodes.py", line 200, in deserialize
return method(data)
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/nodes.py", line 478, in deserialize
for d in data['items']])
File "/home/andrew/.virtualenvs/platform-api-clients/lib/python3.6/site-packages/mypy/nodes.py", line 446, in __init__
assert len(items) > 0
AssertionError

# Fixed code
def __init__(self, items: List["OverloadPart"]) -> None:
    super().__init__()
    self.items = items
    self.unanalyzed_items = items.copy()
    self.impl = None
    if len(items) > 0:
        self.set_line(items[0].line)
    self.is_final = False
# Buggy code
def _make_frozen(
    ctx: "mypy.plugin.ClassDefContext", attributes: List[Attribute]
) -> None:
    """Turn all the attributes into properties to simulate frozen classes."""
    # TODO: Handle subclasses of frozen classes.
    for attribute in attributes:
        node = ctx.cls.info.names[attribute.name].node
        assert isinstance(node, Var)
        node.is_initialized_in_class = False
        node.is_property = True


# Traceback (FrozenInstanceError)
thing = B(foo=1, bar='hi', baz='bye')
thing.foo = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jliu/Projects/lyft/coupons/venv/lib/python3.6/site-packages/attr/_make.py", line 351, in _frozen_setattrs
raise FrozenInstanceError()
attr.exceptions.FrozenInstanceError

# Fixed code
def _make_frozen(
    ctx: "mypy.plugin.ClassDefContext", attributes: List[Attribute]
) -> None:
    """Turn all the attributes into properties to simulate frozen classes."""
    for attribute in attributes:
        if attribute.name in ctx.cls.info.names:
            # This variable belongs to this class so we can modify it.
            node = ctx.cls.info.names[attribute.name].node
            assert isinstance(node, Var)
            node.is_property = True
        else:
            # This variable belongs to a super class so create new Var so we
            # can modify it.
            var = Var(attribute.name, ctx.cls.info[attribute.name].type)
            var.info = ctx.cls.info
            var._fullname = "%s.%s" % (ctx.cls.info.fullname(), var.name())
            ctx.cls.info.names[var.name()] = SymbolTableNode(MDEF, var)
            var.is_property = True
# Buggy code
def conditional_callable_type_map(
    expr: Expression,
    current_type: Optional[Type],
) -> Tuple[TypeMap, TypeMap]:
    """Takes in an expression and the current type of the expression.

    Returns a 2-tuple: The first element is a map from the expression to
    the restricted type if it were callable. The second element is a
    map from the expression to the type it would hold if it weren't
    callable."""
    if not current_type:
        return {}, {}

    if isinstance(current_type, AnyType):
        return {}, {}

    callables, uncallables = partition_by_callable(current_type)

    if len(callables) and len(uncallables):
        callable_map = (
            {expr: UnionType.make_union(callables)} if len(callables) else None
        )
        uncallable_map = (
            {expr: UnionType.make_union(uncallables)} if len(uncallables) else None
        )
        return callable_map, uncallable_map

    elif len(callables):
        return {}, None

    return None, {}


# Traceback (TypeError)
$ mypy n.py
$ python3 n.py
hello
Traceback (most recent call last):
File "n.py", line 8, in <module>
f(lambda: print('hello'))
File "n.py", line 5, in f
1 + 'boom'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

# Fixed code
def conditional_callable_type_map(
    self,
    expr: Expression,
    current_type: Optional[Type],
) -> Tuple[TypeMap, TypeMap]:
    """Takes in an expression and the current type of the expression.

    Returns a 2-tuple: The first element is a map from the expression to
    the restricted type if it were callable. The second element is a
    map from the expression to the type it would hold if it weren't
    callable.
    """
    if not current_type:
        return {}, {}

    if isinstance(current_type, AnyType):
        return {}, {}

    callables, uncallables = self.partition_by_callable(
        current_type, unsound_partition=False
    )

    if len(callables) and len(uncallables):
        callable_map = (
            {expr: UnionType.make_union(callables)} if len(callables) else None
        )
        uncallable_map = (
            {expr: UnionType.make_union(uncallables)} if len(uncallables) else None
        )
        return callable_map, uncallable_map

    elif len(callables):
        return {}, None

    return None, {}
# Buggy code
def check_for_comp(self, e: Union[GeneratorExpr, DictionaryComprehension]) -> None:
    """Check the for_comp part of comprehensions. That is the part from 'for':
    ... for x in y if z

    Note: This adds the type information derived from the condlists to the current binder.
    """
    for index, sequence, conditions, is_async in zip(
        e.indices, e.sequences, e.condlists, e.is_async
    ):
        if is_async:
            sequence_type = self.chk.analyze_async_iterable_item_type(sequence)
        else:
            sequence_type = self.chk.analyze_iterable_item_type(sequence)
        self.chk.analyze_index_variables(index, sequence_type, True, e)
        for condition in conditions:
            self.accept(condition)

            # values are only part of the comprehension when all conditions are true
            true_map, _ = mypy.checker.find_isinstance_check(
                condition, self.chk.type_map
            )

            if true_map:
                for var, type in true_map.items():
                    self.chk.binder.put(var, type)


# Traceback (TypeError)
$ mypy n.py
$ python3 n.py
hello
Traceback (most recent call last):
File "n.py", line 8, in <module>
f(lambda: print('hello'))
File "n.py", line 5, in f
1 + 'boom'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

# Fixed code
def check_for_comp(self, e: Union[GeneratorExpr, DictionaryComprehension]) -> None:
    """Check the for_comp part of comprehensions. That is the part from 'for':
    ... for x in y if z

    Note: This adds the type information derived from the condlists to the current binder.
    """
    for index, sequence, conditions, is_async in zip(
        e.indices, e.sequences, e.condlists, e.is_async
    ):
        if is_async:
            sequence_type = self.chk.analyze_async_iterable_item_type(sequence)
        else:
            sequence_type = self.chk.analyze_iterable_item_type(sequence)
        self.chk.analyze_index_variables(index, sequence_type, True, e)
        for condition in conditions:
            self.accept(condition)

            # values are only part of the comprehension when all conditions are true
            true_map, _ = self.chk.find_isinstance_check(condition)

            if true_map:
                for var, type in true_map.items():
                    self.chk.binder.put(var, type)
# Buggy code
def calculate_mro(self) -> None:
    """Calculate and set mro (method resolution order).

    Raise MroError if cannot determine mro.
    """
    mro = linearize_hierarchy(self)
    assert mro, "Could not produce a MRO at all for %s" % (self,)
    self.mro = mro
    self.is_enum = self._calculate_is_enum()


# Traceback (TypeError)
$ mypy n.py
$ python3 n.py
hello
Traceback (most recent call last):
File "n.py", line 8, in <module>
f(lambda: print('hello'))
File "n.py", line 5, in f
1 + 'boom'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

# Fixed code
def calculate_mro(self) -> None:
    """Calculate and set mro (method resolution order).

    Raise MroError if cannot determine mro.
    """
    mro = linearize_hierarchy(self)
    assert mro, "Could not produce a MRO at all for %s" % (self,)
    self.mro = mro
    self.is_enum = self._calculate_is_enum()
    # The property of falling back to Any is inherited.
    self.fallback_to_any = any(baseinfo.fallback_to_any for baseinfo in self.mro)
# Buggy code
def calculate_class_mro(defn: ClassDef, fail: Callable[[str, Context], None]) -> None:
    try:
        defn.info.calculate_mro()
    except MroError:
        fail(
            "Cannot determine consistent method resolution order "
            '(MRO) for "%s"' % defn.name,
            defn,
        )
        defn.info.mro = []
    # The property of falling back to Any is inherited.
    defn.info.fallback_to_any = any(
        baseinfo.fallback_to_any for baseinfo in defn.info.mro
    )


# Traceback (TypeError)
$ mypy n.py
$ python3 n.py
hello
Traceback (most recent call last):
File "n.py", line 8, in <module>
f(lambda: print('hello'))
File "n.py", line 5, in f
1 + 'boom'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

# Fixed code
def calculate_class_mro(defn: ClassDef, fail: Callable[[str, Context], None]) -> None:
    try:
        defn.info.calculate_mro()
    except MroError:
        fail(
            "Cannot determine consistent method resolution order "
            '(MRO) for "%s"' % defn.name,
            defn,
        )
        defn.info.mro = []
# Buggy code
def mark_interface_stale(self) -> None:
    """Marks this module as having a stale public interface, and discards the cache data."""
    self.meta = None
    self.externally_same = False
    self.manager.stale_modules.add(self.id)


# Traceback (AssertionError)
$ bin/mypy python/
Traceback (most recent call last):
File "bin/mypy", line 33, in <module>
sys.exit(console_entry())
File "dist/lib/python3.6/mypy/__main__.py", line 7, in console_entry
main(None)
File "dist/lib/python3.6/mypy/main.py", line 50, in main
res = type_check_only(sources, bin_dir, options)
File "dist/lib/python3.6/mypy/main.py", line 97, in type_check_only
options=options)
File "dist/lib/python3.6/mypy/build.py", line 196, in build
graph = dispatch(sources, manager)
File "dist/lib/python3.6/mypy/build.py", line 1801, in dispatch
process_graph(graph, manager)
File "dist/lib/python3.6/mypy/build.py", line 2037, in process_graph
process_fresh_scc(graph, prev_scc)
File "dist/lib/python3.6/mypy/build.py", line 2106, in process_fresh_scc
graph[id].fix_cross_refs()
File "dist/lib/python3.6/mypy/build.py", line 1547, in fix_cross_refs
self.manager.options.quick_and_dirty)
File "dist/lib/python3.6/mypy/fixup.py", line 22, in fixup_module_pass_one
node_fixer.visit_symbol_table(tree.names)
File "dist/lib/python3.6/mypy/fixup.py", line 105, in visit_symbol_table
self.visit_type_info(value.node)
File "dist/lib/python3.6/mypy/fixup.py", line 62, in visit_type_info
base.accept(self.type_fixer)
File "dist/lib/python3.6/mypy/types.py", line 435, in accept
return visitor.visit_instance(self)
File "dist/lib/python3.6/mypy/fixup.py", line 176, in visit_instance
assert self.quick_and_dirty, "Should never get here in normal mode"
AssertionError: Should never get here in normal mode

# Fixed code
def mark_interface_stale(self, *, on_errors: bool = False) -> None:
    """Marks this module as having a stale public interface, and discards the cache data."""
    self.meta = None
    self.externally_same = False
    if not on_errors:
        self.manager.stale_modules.add(self.id)
# Buggy code
def is_type_obj(self) -> bool:
    t = self.fallback.type
    return t is not None and t.is_metaclass()


# Traceback (AssertionError)
$ bin/mypy python/
Traceback (most recent call last):
File "bin/mypy", line 33, in <module>
sys.exit(console_entry())
File "dist/lib/python3.6/mypy/__main__.py", line 7, in console_entry
main(None)
File "dist/lib/python3.6/mypy/main.py", line 50, in main
res = type_check_only(sources, bin_dir, options)
File "dist/lib/python3.6/mypy/main.py", line 97, in type_check_only
options=options)
File "dist/lib/python3.6/mypy/build.py", line 196, in build
graph = dispatch(sources, manager)
File "dist/lib/python3.6/mypy/build.py", line 1801, in dispatch
process_graph(graph, manager)
File "dist/lib/python3.6/mypy/build.py", line 2037, in process_graph
process_fresh_scc(graph, prev_scc)
File "dist/lib/python3.6/mypy/build.py", line 2106, in process_fresh_scc
graph[id].fix_cross_refs()
File "dist/lib/python3.6/mypy/build.py", line 1547, in fix_cross_refs
self.manager.options.quick_and_dirty)
File "dist/lib/python3.6/mypy/fixup.py", line 22, in fixup_module_pass_one
node_fixer.visit_symbol_table(tree.names)
File "dist/lib/python3.6/mypy/fixup.py", line 105, in visit_symbol_table
self.visit_type_info(value.node)
File "dist/lib/python3.6/mypy/fixup.py", line 62, in visit_type_info
base.accept(self.type_fixer)
File "dist/lib/python3.6/mypy/types.py", line 435, in accept
return visitor.visit_instance(self)
File "dist/lib/python3.6/mypy/fixup.py", line 176, in visit_instance
assert self.quick_and_dirty, "Should never get here in normal mode"
AssertionError: Should never get here in normal mode

# Fixed code
def is_type_obj(self) -> bool:
    return self.fallback.type.is_metaclass()
# Buggy code
def __init__(
    self,
    item: Union[Instance, AnyType, TypeVarType, TupleType, NoneTyp, CallableType],
    *,
    line: int = -1,
    column: int = -1,
) -> None:
    """To ensure Type[Union[A, B]] is always represented as Union[Type[A], Type[B]], item of
    type UnionType must be handled through make_normalized static method.
    """
    super().__init__(line, column)
    if isinstance(item, CallableType) and item.is_type_obj():
        self.item = item.fallback
    else:
        self.item = item


# Traceback (AssertionError)
$ bin/mypy python/
Traceback (most recent call last):
File "bin/mypy", line 33, in <module>
sys.exit(console_entry())
File "dist/lib/python3.6/mypy/__main__.py", line 7, in console_entry
main(None)
File "dist/lib/python3.6/mypy/main.py", line 50, in main
res = type_check_only(sources, bin_dir, options)
File "dist/lib/python3.6/mypy/main.py", line 97, in type_check_only
options=options)
File "dist/lib/python3.6/mypy/build.py", line 196, in build
graph = dispatch(sources, manager)
File "dist/lib/python3.6/mypy/build.py", line 1801, in dispatch
process_graph(graph, manager)
File "dist/lib/python3.6/mypy/build.py", line 2037, in process_graph
process_fresh_scc(graph, prev_scc)
File "dist/lib/python3.6/mypy/build.py", line 2106, in process_fresh_scc
graph[id].fix_cross_refs()
File "dist/lib/python3.6/mypy/build.py", line 1547, in fix_cross_refs
self.manager.options.quick_and_dirty)
File "dist/lib/python3.6/mypy/fixup.py", line 22, in fixup_module_pass_one
node_fixer.visit_symbol_table(tree.names)
File "dist/lib/python3.6/mypy/fixup.py", line 105, in visit_symbol_table
self.visit_type_info(value.node)
File "dist/lib/python3.6/mypy/fixup.py", line 62, in visit_type_info
base.accept(self.type_fixer)
File "dist/lib/python3.6/mypy/types.py", line 435, in accept
return visitor.visit_instance(self)
File "dist/lib/python3.6/mypy/fixup.py", line 176, in visit_instance
assert self.quick_and_dirty, "Should never get here in normal mode"
AssertionError: Should never get here in normal mode

# Fixed code
def __init__(
    self,
    item: Union[Instance, AnyType, TypeVarType, TupleType, NoneTyp, CallableType],
    *,
    line: int = -1,
    column: int = -1,
) -> None:
    """To ensure Type[Union[A, B]] is always represented as Union[Type[A], Type[B]], item of
    type UnionType must be handled through make_normalized static method.
    """
    super().__init__(line, column)
    self.item = item
# Buggy code
def __init__(
    self,
    typ: mypy.nodes.TypeInfo,
    args: List[Type],
    line: int = -1,
    column: int = -1,
    erased: bool = False,
) -> None:
    assert typ is None or typ.fullname() not in ["builtins.Any", "typing.Any"]
    self.type = typ
    self.args = args
    self.erased = erased
    super().__init__(line, column)


# Traceback (AttributeError)
$ mypy --quick --show-traceback a.py
/Users/jukka/src/mypy/b.py:3: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.510-dev-c856a53fe06c0ad9193d86ab35fb86693940f273-dirty
Traceback (most recent call last):
File "/Users/jukka/src/mypy/scripts/mypy", line 6, in <module>
main(__file__)
File "/Users/jukka/src/mypy/mypy/main.py", line 46, in main
res = type_check_only(sources, bin_dir, options)
File "/Users/jukka/src/mypy/mypy/main.py", line 93, in type_check_only
options=options)
File "/Users/jukka/src/mypy/mypy/build.py", line 188, in build
graph = dispatch(sources, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1570, in dispatch
process_graph(graph, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1813, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1912, in process_stale_scc
graph[id].type_check_first_pass()
File "/Users/jukka/src/mypy/mypy/build.py", line 1485, in type_check_first_pass
self.type_checker.check_first_pass()
File "/Users/jukka/src/mypy/mypy/checker.py", line 177, in check_first_pass
self.accept(d)
File "/Users/jukka/src/mypy/mypy/checker.py", line 262, in accept
stmt.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 823, in accept
return visitor.visit_expression_stmt(self)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1817, in visit_expression_stmt
self.expr_checker.accept(s.expr, allow_none_return=True)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 2056, in accept
typ = node.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 1254, in accept
return visitor.visit_member_expr(self)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 1010, in visit_member_expr
result = self.analyze_ordinary_member_access(e, False)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 1025, in analyze_ordinary_member_access
original_type=original_type, chk=self.chk)
File "/Users/jukka/src/mypy/mypy/checkmember.py", line 74, in analyze_member_access
method = info.get_method(name)
AttributeError: 'NoneType' object has no attribute 'get_method'
/Users/jukka/src/mypy/b.py:3: note: use --pdb to drop into pdb

# Fixed code
def __init__(
    self,
    typ: mypy.nodes.TypeInfo,
    args: List[Type],
    line: int = -1,
    column: int = -1,
    erased: bool = False,
) -> None:
    assert typ is NOT_READY or typ.fullname() not in ["builtins.Any", "typing.Any"]
    self.type = typ
    self.args = args
    self.erased = erased
    super().__init__(line, column)
# Buggy code
def __init__(self, items: List["OverloadPart"]) -> None:
    self.items = items
    self.impl = None
    self.set_line(items[0].line)


# Traceback (IndexError)
# mypy --show-traceback test.py
test.py:26: error: Name 'do_chain' already defined
test.py:22: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.510
Traceback (most recent call last):
File "mypys", line 6, in <module>
main(__file__)
File "/tmp/mypy-0.510/mypy/main.py", line 46, in main
res = type_check_only(sources, bin_dir, options)
File "/tmp/mypy-0.510/mypy/main.py", line 93, in type_check_only
options=options)
File "/tmp/mypy-0.510/mypy/build.py", line 188, in build
graph = dispatch(sources, manager)
File "/tmp/mypy-0.510/mypy/build.py", line 1595, in dispatch
process_graph(graph, manager)
File "/tmp/mypy-0.510/mypy/build.py", line 1838, in process_graph
process_stale_scc(graph, scc, manager)
File "/tmp/mypy-0.510/mypy/build.py", line 1931, in process_stale_scc
graph[id].semantic_analysis()
File "/tmp/mypy-0.510/mypy/build.py", line 1495, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options)
File "/tmp/mypy-0.510/mypy/semanal.py", line 257, in visit_file
self.accept(d)
File "/tmp/mypy-0.510/mypy/semanal.py", line 3288, in accept
node.accept(self)
File "/tmp/mypy-0.510/mypy/nodes.py", line 749, in accept
return visitor.visit_class_def(self)
File "/tmp/mypy-0.510/mypy/semanal.py", line 620, in visit_class_def
defn.defs.accept(self)
File "/tmp/mypy-0.510/mypy/nodes.py", line 810, in accept
return visitor.visit_block(self)
File "/tmp/mypy-0.510/mypy/semanal.py", line 1375, in visit_block
self.accept(s)
File "/tmp/mypy-0.510/mypy/semanal.py", line 3288, in accept
node.accept(self)
File "/tmp/mypy-0.510/mypy/nodes.py", line 409, in accept
return visitor.visit_overloaded_func_def(self)
File "/tmp/mypy-0.510/mypy/semanal.py", line 516, in visit_overloaded_func_def
typ=defn.type)
File "/tmp/mypy-0.510/mypy/nodes.py", line 406, in name
return self.items[0].name()
IndexError: list index out of range
test.py:22: note: use --pdb to drop into pdb

# Fixed code
def __init__(self, items: List["OverloadPart"]) -> None:
    assert len(items) > 0
    self.items = items
    self.impl = None
    self.set_line(items[0].line)
# Buggy code
def add_ancestors(self) -> None:
    # All parent packages are new ancestors.
    ancestors = []
    parent = self.id
    while "." in parent:
        parent, _ = parent.rsplit(".", 1)
        ancestors.append(parent)
    self.ancestors = ancestors


# Traceback (AssertionError)
Traceback (most recent call last):
File "/usr/local/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/local/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/guido/src/mypy/mypy/__main__.py", line 5, in <module>
main(None)
File "/Users/guido/src/mypy/mypy/main.py", line 38, in main
sources, options = process_options(sys.argv[1:])
File "/Users/guido/src/mypy/mypy/main.py", line 364, in process_options
targets.append(BuildSource(f, crawl_up(f)[1], None))
File "/Users/guido/src/mypy/mypy/main.py", line 429, in crawl_up
assert '.' not in mod
AssertionError

# Fixed code
def add_ancestors(self) -> None:
    if self.path is not None:
        _, name = os.path.split(self.path)
        base, _ = os.path.splitext(name)
        if "." in base:
            # This is just a weird filename, don't add anything
            self.ancestors = []
            return
    # All parent packages are new ancestors.
    ancestors = []
    parent = self.id
    while "." in parent:
        parent, _ = parent.rsplit(".", 1)
        ancestors.append(parent)
    self.ancestors = ancestors
# Buggy code
def crawl_up(arg: str) -> Tuple[str, str]:
    """Given a .py[i] filename, return (root directory, module).

    We crawl up the path until we find a directory without
    __init__.py[i], or until we run out of path components.
    """
    dir, mod = os.path.split(arg)
    mod = strip_py(mod) or mod
    assert "." not in mod
    while dir and get_init_file(dir):
        dir, base = os.path.split(dir)
        if not base:
            break
        if mod == "__init__" or not mod:
            mod = base
        else:
            mod = base + "." + mod
    return dir, mod


# Traceback (AssertionError)
Traceback (most recent call last):
File "/usr/local/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/local/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/guido/src/mypy/mypy/__main__.py", line 5, in <module>
main(None)
File "/Users/guido/src/mypy/mypy/main.py", line 38, in main
sources, options = process_options(sys.argv[1:])
File "/Users/guido/src/mypy/mypy/main.py", line 364, in process_options
targets.append(BuildSource(f, crawl_up(f)[1], None))
File "/Users/guido/src/mypy/mypy/main.py", line 429, in crawl_up
assert '.' not in mod
AssertionError

# Fixed code
def crawl_up(arg: str) -> Tuple[str, str]:
    """Given a .py[i] filename, return (root directory, module).

    We crawl up the path until we find a directory without
    __init__.py[i], or until we run out of path components.
    """
    dir, mod = os.path.split(arg)
    mod = strip_py(mod) or mod
    while dir and get_init_file(dir):
        dir, base = os.path.split(dir)
        if not base:
            break
        if mod == "__init__" or not mod:
            mod = base
        else:
            mod = base + "." + mod
    return dir, mod
# Buggy code
def main(script_path: str) -> None:
    """Main entry point to the type checker.

    Args:
        script_path: Path to the 'mypy' script (used for finding data files).
    """
    t0 = time.time()
    if script_path:
        bin_dir = find_bin_directory(script_path)
    else:
        bin_dir = None
    sys.setrecursionlimit(2**14)
    sources, options = process_options(sys.argv[1:])
    serious = False
    try:
        res = type_check_only(sources, bin_dir, options)
        a = res.errors
    except CompileError as e:
        a = e.messages
        if not e.use_stdout:
            serious = True
    if options.junit_xml:
        t1 = time.time()
        util.write_junit_xml(t1 - t0, serious, a, options.junit_xml)
    if a:
        f = sys.stderr if serious else sys.stdout
        for m in a:
            f.write(m + "\n")
        sys.exit(1)


# Traceback (BrokenPipeError)
Traceback (most recent call last):
File "/home/.../bin/mypy", line 6, in <module>
main(__file__)
File "/home/.../lib/python3.5/site-packages/mypy/main.py", line 53, in main
f.write(m + '\n')
BrokenPipeError: [Errno 32] Broken pipe

# Fixed code
def main(script_path: str) -> None:
    """Main entry point to the type checker.

    Args:
        script_path: Path to the 'mypy' script (used for finding data files).
    """
    t0 = time.time()
    if script_path:
        bin_dir = find_bin_directory(script_path)
    else:
        bin_dir = None
    sys.setrecursionlimit(2**14)
    sources, options = process_options(sys.argv[1:])
    serious = False
    try:
        res = type_check_only(sources, bin_dir, options)
        a = res.errors
    except CompileError as e:
        a = e.messages
        if not e.use_stdout:
            serious = True
    if options.junit_xml:
        t1 = time.time()
        util.write_junit_xml(t1 - t0, serious, a, options.junit_xml)
    if a:
        f = sys.stderr if serious else sys.stdout
        try:
            for m in a:
                f.write(m + "\n")
        except BrokenPipeError:
            pass
        sys.exit(1)
# Buggy code
def _add_dependencies(self, key: Key, value: Key = None) -> None:
    if value is None:
        value = key
    else:
        self.dependencies.setdefault(key, set()).add(value)
    if isinstance(key, tuple):
        for elt in key:
            self._add_dependencies(elt, value)


# Traceback (AttributeError)
Traceback (most recent call last):
File "./scripts/mypy", line 6, in <module>
main(__file__)
File "mypy/mypy/main.py", line 50, in main
type_check_only(sources, bin_dir, options)
File "mypy/mypy/main.py", line 94, in type_check_only
python_path=options.python_path)
File "mypy/mypy/build.py", line 210, in build
result = manager.process(initial_states)
File "mypy/mypy/build.py", line 425, in process
next.process()
File "mypy/mypy/build.py", line 930, in process
self.type_checker().visit_file(self.tree, self.tree.path)
File "mypy/mypy/checker.py", line 409, in visit_file
self.accept(d)
File "mypy/mypy/checker.py", line 450, in accept
typ = node.accept(self)
File "mypy/mypy/nodes.py", line 707, in accept
return visitor.visit_try_stmt(self)
File "mypy/mypy/checker.py", line 1732, in visit_try_stmt
self.accept(s.else_body)
File "mypy/mypy/checker.py", line 450, in accept
typ = node.accept(self)
File "mypy/mypy/nodes.py", line 526, in accept
return visitor.visit_block(self)
File "mypy/mypy/checker.py", line 1113, in visit_block
self.accept(s)
File "mypy/mypy/checker.py", line 450, in accept
typ = node.accept(self)
File "mypy/mypy/nodes.py", line 382, in accept
return visitor.visit_func_def(self)
File "mypy/mypy/checker.py", line 594, in visit_func_def
'redefinition with type')
File "mypy/mypy/checker.py", line 2117, in check_subtype
if not is_subtype(subtype, supertype):
File "mypy/mypy/subtypes.py", line 49, in is_subtype
return left.accept(SubtypeVisitor(right, type_parameter_checker))
AttributeError: 'NoneType' object has no attribute 'accept'

# Fixed code
def _add_dependencies(self, key: Key, value: Key = None) -> None:
    if value is None:
        value = key
    else:
        self.dependencies.setdefault(key, set()).add(value)
    for elt in key:
        if isinstance(elt, Key):
            self._add_dependencies(elt, value)
# Buggy code
def pop_frame(self, fall_through: int = 0) -> Frame:
    """Pop a frame and return it.

    See frame_context() for documentation of fall_through.
    """
    if fall_through and not self.breaking_out:
        self.allow_jump(-fall_through)

    result = self.frames.pop()
    options = self.options_on_return.pop()

    self.last_pop_changed = self.update_from_options(options)
    self.last_pop_breaking_out = self.breaking_out

    return result


# Traceback (AttributeError)
Traceback (most recent call last):
File "./scripts/mypy", line 6, in <module>
main(__file__)
File "mypy/mypy/main.py", line 50, in main
type_check_only(sources, bin_dir, options)
File "mypy/mypy/main.py", line 94, in type_check_only
python_path=options.python_path)
File "mypy/mypy/build.py", line 210, in build
result = manager.process(initial_states)
File "mypy/mypy/build.py", line 425, in process
next.process()
File "mypy/mypy/build.py", line 930, in process
self.type_checker().visit_file(self.tree, self.tree.path)
File "mypy/mypy/checker.py", line 409, in visit_file
self.accept(d)
File "mypy/mypy/checker.py", line 450, in accept
typ = node.accept(self)
File "mypy/mypy/nodes.py", line 707, in accept
return visitor.visit_try_stmt(self)
File "mypy/mypy/checker.py", line 1732, in visit_try_stmt
self.accept(s.else_body)
File "mypy/mypy/checker.py", line 450, in accept
typ = node.accept(self)
File "mypy/mypy/nodes.py", line 526, in accept
return visitor.visit_block(self)
File "mypy/mypy/checker.py", line 1113, in visit_block
self.accept(s)
File "mypy/mypy/checker.py", line 450, in accept
typ = node.accept(self)
File "mypy/mypy/nodes.py", line 382, in accept
return visitor.visit_func_def(self)
File "mypy/mypy/checker.py", line 594, in visit_func_def
'redefinition with type')
File "mypy/mypy/checker.py", line 2117, in check_subtype
if not is_subtype(subtype, supertype):
File "mypy/mypy/subtypes.py", line 49, in is_subtype
return left.accept(SubtypeVisitor(right, type_parameter_checker))
AttributeError: 'NoneType' object has no attribute 'accept'

# Fixed code
def pop_frame(self, can_skip: bool, fall_through: int) -> Frame:
    """Pop a frame and return it.

    See frame_context() for documentation of fall_through.
    """

    if fall_through > 0:
        self.allow_jump(-fall_through)

    result = self.frames.pop()
    options = self.options_on_return.pop()

    if can_skip:
        options.insert(0, self.frames[-1])

    self.last_pop_changed = self.update_from_options(options)

    return result
# Buggy code
def get_declaration(self, node: Node) -> Type:
    if isinstance(node, (RefExpr, SymbolTableNode)) and isinstance(node.node, Var):
        type = node.node.type
        if isinstance(type, PartialType):
            return None
        return type
    else:
        return None


# Traceback (AttributeError)
Traceback (most recent call last):
File "./scripts/mypy", line 6, in <module>
main(__file__)
File "mypy/mypy/main.py", line 50, in main
type_check_only(sources, bin_dir, options)
File "mypy/mypy/main.py", line 94, in type_check_only
python_path=options.python_path)
File "mypy/mypy/build.py", line 210, in build
result = manager.process(initial_states)
File "mypy/mypy/build.py", line 425, in process
next.process()
File "mypy/mypy/build.py", line 930, in process
self.type_checker().visit_file(self.tree, self.tree.path)
File "mypy/mypy/checker.py", line 409, in visit_file
self.accept(d)
File "mypy/mypy/checker.py", line 450, in accept
typ = node.accept(self)
File "mypy/mypy/nodes.py", line 707, in accept
return visitor.visit_try_stmt(self)
File "mypy/mypy/checker.py", line 1732, in visit_try_stmt
self.accept(s.else_body)
File "mypy/mypy/checker.py", line 450, in accept
typ = node.accept(self)
File "mypy/mypy/nodes.py", line 526, in accept
return visitor.visit_block(self)
File "mypy/mypy/checker.py", line 1113, in visit_block
self.accept(s)
File "mypy/mypy/checker.py", line 450, in accept
typ = node.accept(self)
File "mypy/mypy/nodes.py", line 382, in accept
return visitor.visit_func_def(self)
File "mypy/mypy/checker.py", line 594, in visit_func_def
'redefinition with type')
File "mypy/mypy/checker.py", line 2117, in check_subtype
if not is_subtype(subtype, supertype):
File "mypy/mypy/subtypes.py", line 49, in is_subtype
return left.accept(SubtypeVisitor(right, type_parameter_checker))
AttributeError: 'NoneType' object has no attribute 'accept'

# Fixed code
def get_declaration(self, expr: Node) -> Type:
    if isinstance(expr, RefExpr) and isinstance(expr.node, Var):
        type = expr.node.type
        if isinstance(type, PartialType):
            return None
        return type
    else:
        return None