Wemake-python-styleguide: Forbid getting first element using unpacking

Created on 19 Jan 2021  路  3Comments  路  Source: wemake-services/wemake-python-styleguide

Rule request

Thesis

# bad
first, *_rest = some_collection

# good
first = some_collection[0]

# also good, works with any iterator
first = next(iter(collection))

Reasoning

Performance. Prefixing unused variables with underscore is nothing more than convention, Python still creates these variables. So, unpacking above makes a new unused list which is slow.

lst = list(range(10_000))

# fast
%%timeit
a = lst[0]
# 32 ns 卤 1.29 ns per loop

# 2-3 times slower but works with any iterator
%%timeit
a = next(iter(lst))
# 83.1 ns 卤 6.38 ns per loop

# 1000 times slower!
%%timeit
a, *_ = lst
# 32.9 碌s 卤 885 ns per loop
help wanted starter rule request

Most helpful comment

I would say that head, *tail = some_collection is fine. In case we are going to use both head and tail.

The usecase for this rule is when _tail is unused.

All 3 comments

I would say that head, *tail = some_collection is fine. In case we are going to use both head and tail.

The usecase for this rule is when _tail is unused.

Exactly! The rule request is about the case when unpacking is used to get only the first element. Prefix _ should be a good enough indication that the variable is unused.

--

BTW, F841 is not effective for catching unused variables in unpacking for some reason.

This fails:

head, *tail = [1, 2, 3]
print(head)

This doesn't:

items = [1, 2, 3]
head, *tail = items
print(head)

I'm wondering if it makes sense to implement a better "variable is assigned to but never used" check on the WPS side. It's a bit offtopic, though.

I add PR for this (github did not link it, I do not know why) :

https://github.com/wemake-services/wemake-python-styleguide/pull/1927

UPD: I just entered wrong issue number

Was this page helpful?
0 / 5 - 0 ratings