wemake-python-styleguide icon indicating copy to clipboard operation
wemake-python-styleguide copied to clipboard

Forbid complex grammar in slice

Open MIXgleb opened this issue 5 months ago • 2 comments

Rule request

Allow only a name, constant, and attribute in slice args.

Thesis

Correct: array[3:7] array[start_index:end_index] array[index.start:index.end]

Wrong: array[my_dict["start_index"]:my_list[-1]] array[start_index():index.end()]

Should be:

start_index = my_dict["start_index"]
end_index = my_list[-1]
new_array = array[start_index:end_index]
start_index = start_index()
end_index = index.end()
new_array = array[start_index:end_index]

Reasoning

Complex grammar are difficult to read and should be stored in separate vars.

It's really difficult to review such many dependent constructions: new_array = array[my_dict[":"]::get_step()]

It might also be worth forbidding an attribute, but I don't think it's a complex grammar.

class Slice:
    class MyArray:
        start = 1
        end = 1

new_array = array[Slice.MyArray.start:]

But not new_array = array[Slice(arg_1).MyArray(arg_2, arg_3).start:]

MIXgleb avatar May 21 '25 13:05 MIXgleb