Skip to content

Conversation

@BobTheBuidler
Copy link
Contributor

This will create optimized code paths for:

  • for x in seq[1:]
  • for x in seq[1:2]
  • for x in seq[1:-1]
  • for x in seq[:] # TODO: exempt this, its invalid
  • for x in seq[:2]
  • for x in seq[:-1]
  • for x in seq[1::-1]
  • for x in seq[1:2:-1]
  • for x in seq[1:-1:-1]
  • for x in seq[:2:-1]
  • for x in seq[:-1:-1]

There is no reason to actually create a sliced sequence from the original sequence when we can just grab the appropriate items from the original sequence. We are already grabbing the same number of items from the sliced sequence anyway.

(Explain how this PR changes mypy.)

BobTheBuidler and others added 11 commits October 23, 2025 09:06
This will create optimized code paths for:
- `for x in seq[1:]`
- `for x in seq[1:2]`
- `for x in seq[1:-1]`
- `for x in seq[:]`  # TODO: exempt this, its invalid
- `for x in seq[:2]`
- `for x in seq[:-1]`
- `for x in seq[1::-1]`
- `for x in seq[1:2:-1]`
- `for x in seq[1:-1:-1]`
- `for x in seq[:2:-1]`
- `for x in seq[:-1:-1]`

There is no reason to actually create a sliced sequence from the original sequence when we can just grab the appropriate items from the original sequence. We are already grabbing the same number of items from the sliced sequence anyway.
assert self.stop == -1, "implement me!"

self.step = 1 if step is None else step
assert self.step and self.step >= 1, "this should be unreachable for step None and step 0"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is currently reachable

@BobTheBuidler BobTheBuidler changed the title [mypyc] feat: enhance ForSequence with start, stop, step [mypyc] feat: enhance ForSequence with start, stop, step for IndexExpr case Oct 24, 2025

if isinstance(expr, IndexExpr) and isinstance(expr.index, SliceExpr):
# TODO: maybe we must not apply this optimization to list type specifically
# because the need to check length changes at each iteration?
Copy link
Contributor Author

@BobTheBuidler BobTheBuidler Oct 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can probably still be valid for ListComp and ListExpr

def do_thing():
    return [x + 4 for x in some_non_reversible_generator][1:-2:-1]

not sure how useful that is though

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.

1 participant