Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Forbid implicit slice #2302

Closed
thecnoNSMB opened this issue Dec 16, 2021 · 1 comment
Closed

Forbid implicit slice #2302

thecnoNSMB opened this issue Dec 16, 2021 · 1 comment
Labels
rule request Adding a new rule

Comments

@thecnoNSMB
Copy link

Rule request

Forbid looping constructs over indexes that are equivalent to slice operations.

Thesis

I recently encountered a point in my code where I was using a comprehension to iterate over a range to index into a list. Here is a basic example that currently passes all checks:

my_list = [1, 2, 3, 4, 5]

# Wrong:
my_sublist = [my_list[index] for index in range(1, 4)]

# Right:
my_sublist = my_list[1:4]

A trickier example closer to what I found:

some_text = 'Python!'

an_index = 4

# Wrong (but fails on Jones complexity):
subset = {some_text[index] for index in range(an_index - 1, an_index - 4, -1)}

# Right:
subset = set(some_text[an_index - 3:an_index])

Reasoning

These are redundant, probably slower, and harder to read.

@thecnoNSMB thecnoNSMB added the rule request Adding a new rule label Dec 16, 2021
@sobolevn
Copy link
Member

The problem is that my_list can possibly not support slice operaions. For example, it can be a dict or QuerySet object, or something else.

I don't think that this rule can be safe without knowing the type of the object. Will be implemented in typed-linter 🌚

@sobolevn sobolevn closed this as not planned Won't fix, can't repro, duplicate, stale Dec 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
rule request Adding a new rule
Projects
None yet
Development

No branches or pull requests

2 participants