astral-sh / astral-sh/ruff

PLR6201 should only hit for membership test on constant collections

Open
#8,322 2 comments 2 reactions 0 assignees View on GitHub
rule
Dominant language
Rust
Stars
49.6k
Forks
2.4k
Avg merge
2d 1h
Merged PRs (30d)
458

Description

### Ruff version

ruff 0.1.3

### Ruff settings

Just make sure PLR6201 is enabled

### Problem

```python
a = 1
b = 2
x = 5

test1 = 2 in [1, 2, 3]
test2 = 'c' in ('a', 'b', 'c')
test3 = x in (a, b)
```

Run ruff on this one.

It will hit you with something like:

```
test4.py:5:14: PLR6201 Use a `set` literal when testing for membership
test4.py:6:16: PLR6201 Use a `set` literal when testing for membership
test4.py:7:14: PLR6201 Use a `set` literal when testing for membership
Found 3 errors.
No fixes available (3 hidden fixes can be enabled with the `--unsafe-fixes` option).
```

As far as I understand this rule should only hit us for **constant** collections as the optimization in question mentions: https://docs.python.org/3/whatsnew/3.2.html#optimizations . So I would not expect to see it in test3.

For collections that have variables inside the optimizer does not, or more like can not do anything so initializing a set does not help in any way and incurs the set initialization "penalty" which the optimizer fixes for constant values.

Does this make sense?

Contributor guide

Open the contributing guide

Research direction

Run Ruff with PLR6201 enabled on the provided Python snippet to reproduce the warning for test3. Then inspect the PLR6201 implementation and its tests, and update the behavior so membership tests with non-constant collection elements are not flagged while the constant cases remain covered.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.