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

Is PLR6201 technically incorrect? #9604

Closed
trag1c opened this issue Jan 22, 2024 · 2 comments
Closed

Is PLR6201 technically incorrect? #9604

trag1c opened this issue Jan 22, 2024 · 2 comments

Comments

@trag1c
Copy link
Contributor

trag1c commented Jan 22, 2024

From the docs:

When testing for membership in a static sequence, prefer a set literal over a list or tuple, as Python optimizes set membership tests.

This optimization isn't significant when using literals—while sets do have faster membership checks, doing 1 in (1, 2, 3) is faster than 1 in {1, 2, 3} as it takes 4–5x as much time to just construct a set compared to a tuple (see benchmarks below).

Benchmarks

Creating an object with elements 1, 2, 3

Version tuple set list tuple vs set list vs set
3.12 10.28ns 48.71ns 42.37ns +374% +15%
3.11 8.24ns 39.88ns 25.55ns +384% +56%
3.10 7.98ns 40.73ns 26.86ns +410% +52%
3.9 8.73ns 40.00ns 26.03ns +358% +54%
3.8 9.43ns 39.84ns 27.38ns +322% +46%

Checking whether 1 is a member of the object (w/ a literal)

Version tuple set list tuple vs set list vs set
3.12 15.19ns 16.54ns 15.20ns +9% +9%
3.11 13.47ns 14.74ns 14.14ns +9% +4%
3.10 13.83ns 15.20ns 13.83ns +10% +10%
3.9 15.66ns 16.94ns 15.61ns +8% +9%
3.8 17.83ns 19.00ns 17.81ns +7% +7%

Therefore (even though the difference isn't that substantial) I think it would make more sense for the rule to suggest

  • using a tuple when checking against a literal, e.g. 1 in (1, 2, 3), and
  • using a set when checking against a constant, e.g. S = {1, 2, 3}; 1 in S (although I suspect literals may be faster than constants for small objects (because of variable lookup?), in which case tuples would be the way).

Hopefully I haven't made any mistakes with my reasoning 😄

@charliermarsh
Copy link
Member

I think this was discussed a bit in #8758. Do you mind reading that issue first?

@trag1c
Copy link
Contributor Author

trag1c commented Jan 22, 2024

I somehow missed this specific one, my bad—seems like I missed a lot of details here, so I guess it's fine to keep it the way it is in most cases 🙂

@trag1c trag1c closed this as not planned Won't fix, can't repro, duplicate, stale Jan 22, 2024
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

No branches or pull requests

2 participants