tonybaloney / perflint

Python Linter for performance anti patterns
MIT License
659 stars 10 forks source link

Enhancement: suggest set when testing membership of a list or tuple #42

Closed tekumara closed 8 months ago

tekumara commented 1 year ago

Suggest a set when checking membership of a list/tuple of hashable values.

eg:

if fruit in {"orange", "apple"}:

rather than

if fruit in ("orange", "apple"):

or

if fruit in ["orange", "apple"]:

See also https://docs.sourcery.ai/Reference/Python/Default-Rules/collection-into-set/

mqyhlkahu commented 1 year ago

Could also suggest calling set on an iterable before checking membership? e.g.

for foo in iterable_of_foos:
    if foo in bar_iterable:
        do_something(foo)

->

bar_set = set(bar_iterable)
for foo in iterable_of_foos:
    if foo in bar_set:
        do_something(foo)
jenstroeger commented 8 months ago

@tekumara that’s already an optional checker ini pylint: Set Membership checker.

tekumara commented 8 months ago

Oh right thank you, I don't use pylint so wasn't aware it had this check. If possible, could perflint include this too so all the performance related checks are together?

jenstroeger commented 8 months ago

@tekumara have you also looked at ruff’s performance lint implementation here?

tekumara commented 8 months ago

oh yes! I'm using ruff rather than pylint or perflint directly 🙂

I thought to raise the issue here, as this is the upstream. Once implemented here, I'd hope ruff would implement it too.

jenstroeger commented 8 months ago

Well, I think @tonybaloney can find inspiration in pylint’s set_membership.py module.

Although, looking at the inactivity of this repo over the past months I do worry that this package is getting stale… 🤔

tonybaloney commented 8 months ago

Well, I think @tonybaloney can find inspiration in pylint’s set_membership.py module.

Although, looking at the inactivity of this repo over the past months I do worry that this package is getting stale… 🤔

Sorry. I'm on a long overdue break. This is on my list for next week

jenstroeger commented 8 months ago

@tonybaloney oh that’s great to know 👍🏼 Enjoy your break!

tonybaloney commented 8 months ago

perflint is a plugin to pylint so you can run both together. I don't want to duplicate rules that already exist in pylint

tonybaloney commented 8 months ago

https://pylint.pycqa.org/en/latest/user_guide/messages/refactor/use-set-for-membership.html closing. thanks for the idea