Skip to content

[mypyc] Fix loops on reversed lists with Any item types - #22445

Open
PratyushD21 wants to merge 2 commits into
python:masterfrom
PratyushD21:fix-mypyc-reversed-any
Open

PratyushD21 wants to merge 2 commits into
python:masterfrom
PratyushD21:fix-mypyc-reversed-any

Conversation

@PratyushD21

Copy link
Copy Markdown

Fixes #22354

As shared in the issue, if there is a for loop on a reversed iterator, then the mypyc compiler crashes. This was happening because, in the for_helpers.py file, the call was being inferred as Any, instead of inferring the type of the iterator item.

This fix uses the existing iterable analysis method and fetches the rtype.

Regression tests (test name: testForReversedAny) cover lists and tuples containing Any, comprehensions, tuple unpacking, and a NewType backed by a list. The NewType was introduced to showcase why the suggested fix in the original issue will not work. (The suggested fix in the issue was to look up for the argument passed to reversed(). Instead, the current fix is a more general way to find the item type.)

Tests:

  • .venv/bin/python -m pytest -n0 mypyc/test/test_run.py -k testForReversedAny
  • python -m pytest mypyc/test -rx

In addition, while trying to check why the existing test suite had missed this issue, I noticed that the lightweight builtins fixture in mypyc/test-data/fixtures/ir.py has a simplified definition of reversed() which is not accurate as per the python docs. As per Python data model documentation of object.__reversed__(), reversed() should be using __reversed__() when available or otherwise falling back to __len__() and __getitem__().
I have fixed this by overloading the reversed() function to be in-line with the Python object model documentation.

@PratyushD21

Copy link
Copy Markdown
Author

Hi @p-sawicki, @JukkaL,

I have made the change to how the reversed function is overloaded based on the Python documentation. If you feel that the previous implementation for Sequence to Iterator was fine (while still overloading to handle for __reversed__, to catch the bug in mypyc compiling) then I can do that change.

Happy to discuss your inputs!

Thanks a lot!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant