Visitar URL original
[mypyc] AssertionError in get_sequence_type_from_type on `for x in reversed(<list>)` when the item type contains Any · Issue #22354 · python/mypy · GitHub
Skip to content

[mypyc] AssertionError in get_sequence_type_from_type on for x in reversed(<list>) when the item type contains Any #22354

Open

Description

@rob2244

Crash Report

mypyc crashes with an internal error when it compiles a for loop or a comprehension over reversed(seq), where seq is a list or tuple whose item type is Any or contains Any (for example list[Any], list[tuple[int, Any]] or tuple[Any, ...]). mypy itself accepts the code with no errors.

The cause appears to be in the for x in reversed(<list>) fast path of make_for_loop_generator (mypyc/irbuild/for_helpers.py). It checks that the argument is a sequence (is_sequence_rprimitive(builder.node_type(expr.args[0]))), but then takes the item type from the type of the call: builder.get_sequence_type(expr). Because reversed.__new__ is overloaded, mypy infers the call as plain Any when the argument's item type contains Any (several overloads match), so get_sequence_type_from_type gets AnyType and hits assert False, target_type:

$ mypy -c 'from typing import Any
def f(x: list[Any], z: list[int]) -> None:
    reveal_type(reversed(x)); reveal_type(reversed(z))'
<string>:3: note: Revealed type is "Any"
<string>:3: note: Revealed type is "typing.Iterator[int]"

With list[object] or list[tuple[int, str]] the call is typed Iterator[...] and compilation works. With a plain Any argument (x: Any) the fast path is not taken and compilation also works.

A local patch that takes the item type from the argument, as the plain for x in <list> path does, fixes all the cases below, and the compiled code gives the correct results:

             # Special case "for x in reversed(<list>)".
             expr_reg = builder.accept(expr.args[0])
-            target_type = builder.get_sequence_type(expr)
+            target_type = builder.get_sequence_type(expr.args[0])

(I did not run mypyc's own test suite against that patch.)

Traceback

With the compiled mypy wheel from PyPI there is no traceback, only:

Traceback (most recent call last):
crash.py:3: AssertionError: Any
crash.py:3: note: this is an internal mypyc error; please report a bug at https://github.com/mypyc/mypyc/issues

With mypy installed from source (uv pip install --no-binary mypy mypy==2.4.1), mypyc --show-traceback crash.py gives (site-packages paths shortened):

Traceback (most recent call last):
  File "build/setup.py", line 6, in <module>
    ext_modules=mypycify(
  File ".../site-packages/mypyc/build.py", line 975, in mypycify
    groups, group_cfilenames, source_deps = mypyc_build(
  File ".../site-packages/mypyc/build.py", line 727, in mypyc_build
    group_cfiles, ops_text, source_deps = generate_c(
  File ".../site-packages/mypyc/build.py", line 347, in generate_c
    modules, ctext, mapper = emitmodule.compile_modules_to_c(
  File ".../site-packages/mypyc/codegen/emitmodule.py", line 583, in compile_modules_to_c
    modules = compile_modules_to_ir(result, mapper, compiler_options, errors)
  File ".../site-packages/mypyc/codegen/emitmodule.py", line 357, in compile_modules_to_ir
    scc_ir = compile_scc_to_ir(trees, result, mapper, compiler_options, errors)
  File ".../site-packages/mypyc/codegen/emitmodule.py", line 285, in compile_scc_to_ir
    modules = build_ir(scc, result.graph, result.types, mapper, compiler_options, errors)
  File ".../lib/python3.14/contextlib.py", line 85, in inner
    return func(*args, **kwds)
  File ".../site-packages/mypyc/irbuild/main.py", line 115, in build_ir
    transform_mypy_file(builder, module)
  File ".../site-packages/mypyc/irbuild/main.py", line 168, in transform_mypy_file
    builder.accept(node)
  File ".../site-packages/mypyc/irbuild/builder.py", line 373, in accept
    node.accept(self.visitor)
  File ".../site-packages/mypy/nodes.py", line 1165, in accept
    return visitor.visit_func_def(self)
  File ".../site-packages/mypyc/irbuild/visitor.py", line 183, in visit_func_def
    transform_func_def(self.builder, fdef)
  File ".../site-packages/mypyc/irbuild/function.py", line 100, in transform_func_def
    func_ir, func_reg = gen_func_item(builder, fdef, fdef.name, sig)
  File ".../site-packages/mypyc/irbuild/function.py", line 282, in gen_func_item
    func_ir, func_reg = gen_func_body(builder, sig, cdef, is_singledispatch)
  File ".../site-packages/mypyc/irbuild/function.py", line 302, in gen_func_body
    builder.accept(builder.fn_info.fitem.body)
  File ".../site-packages/mypyc/irbuild/builder.py", line 373, in accept
    node.accept(self.visitor)
  File ".../site-packages/mypy/nodes.py", line 1830, in accept
    return visitor.visit_block(self)
  File ".../site-packages/mypyc/irbuild/visitor.py", line 192, in visit_block
    transform_block(self.builder, block)
  File ".../site-packages/mypyc/irbuild/statement.py", line 153, in transform_block
    builder.accept(stmt)
  File ".../site-packages/mypyc/irbuild/builder.py", line 373, in accept
    node.accept(self.visitor)
  File ".../site-packages/mypy/nodes.py", line 2011, in accept
    return visitor.visit_for_stmt(self)
  File ".../site-packages/mypyc/irbuild/visitor.py", line 216, in visit_for_stmt
    transform_for_stmt(self.builder, stmt)
  File ".../site-packages/mypyc/irbuild/statement.py", line 662, in transform_for_stmt
    for_loop_helper(
  File ".../site-packages/mypyc/irbuild/for_helpers.py", line 128, in for_loop_helper
    for_gen = make_for_loop_generator(
  File ".../site-packages/mypyc/irbuild/for_helpers.py", line 588, in make_for_loop_generator
    target_type = builder.get_sequence_type(expr)
  File ".../site-packages/mypyc/irbuild/builder.py", line 1123, in get_sequence_type
    return self.get_sequence_type_from_type(self.types[expr])
  File ".../site-packages/mypyc/irbuild/builder.py", line 1152, in get_sequence_type_from_type
    assert False, target_type
crash.py:3: AssertionError: Any
crash.py:3: note: this is an internal mypyc error; please report a bug at https://github.com/mypyc/mypyc/issues

To Reproduce

crash.py:

from typing import Any


def f(x: list[Any]) -> None:
    for c in reversed(x):
        pass
uv venv -p 3.14 .venv
uv pip install -p .venv mypy==2.4.1 setuptools
.venv/bin/mypyc crash.py

Each of these crashes the same way (each tested as its own module):

from typing import Any

def a(x: list[tuple[int, Any]]) -> None:
    for i, c in reversed(x):
        pass

def b(x: tuple[Any, ...]) -> None:
    for c in reversed(x):
        pass

def c(x: list[Any]) -> list[Any]:
    return [v for v in reversed(x)]

def d(columns: list[Any]) -> dict[Any, int]:
    return {col[1]: i for i, col in reversed(list(enumerate(columns)))}

These compile and run correctly:

from typing import Any

def ok1(x: Any) -> None:                       # argument itself is Any: fast path not taken
    for c in reversed(x):
        pass

def ok2(x: list[tuple[int, object]]) -> None:  # no Any in the item type
    for i, c in reversed(x):
        pass

def ok3(x: list[Any]) -> None:                 # slice instead of reversed()
    for c in x[::-1]:
        pass

The original code was a dict comprehension like d above, in a larger project; we replaced reversed(...) with [::-1] as a workaround.

Your Environment

  • Mypy version used: 2.4.1 (latest release, PyPI wheel and source install); also reproduced on master at ccbf32b (2.5.0+dev)
  • Mypy command-line flags: none (mypyc crash.py)
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.14.3 (uv-managed CPython)
  • Operating system and version: macOS 26.5.2, arm64 (Apple silicon)

Possibly related (same assertion, different code path, already fixed): #20341.

Activity

  1. darshpatel1052 commented on Nov 3, 2026

    @darshpatel1052

    Hi, I’d like to work on this. I’d extend the reversed-loop compiler tests with lists and tuples containing Any, trace item-type selection in the fast path, and compare compiled results with Python for loops and comprehensions. Is taking the type from the sequence argument the preferred fix, or should overload inference be addressed first?

  2. PratyushD21 commented on Nov 12, 2026

    @PratyushD21

    /take

    Hi, since this was still open, I have added a PR for this. The suggested fix is essentially finding the type from the existing iterable analysis. Happy to discuss if I can add anything more to this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions