-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
Feature request: Add rule to detect potential unintended string iteration #14007
Comments
@AlexWaygood I would value your opinion on this. To me, using |
Iteration over the characters of a string is a useful Python feature that's never going to go away. It's also one of the most common footguns in Python programming; there have been many requests to Python type checkers (let alone linters) to try to tackle this problem, and pytype actually implements a version of this. For examples, see:
There's definitely a strong user need for rules that can warn about this, even if they will necessarily come with false positives for the (rare) occasion when you really do need to iterate over the characters of a string. So I think we should definitely explore implementing this check... But it will probably have to wait until we migrate to using red-knot as the backend for Ruff (it needs strong type inference). |
I agree that there are legitimate cases for iterating over characters of a string and I find the syntax elegant, but I'd prefer to make the intent explicit (or turn off the rule for projects that use it often), so thank you for the update! Is #11653 the right issue to follow for the red-knot move? |
Unfortunately that's just one subtask we need to get to for an initial release of red-knot (and it will be only after the initial red-knot release that we'll start migrating Ruff rules to use red-knot as the backend). So it will probably be a while, I'm afraid :-) |
Problem Statement
Python strings being sequences can lead to unintended character-by-character iteration, which is a common source of bugs (https://mail.python.org/pipermail/python-3000/2006-April/000759.html is 2006!). Currently, there's no built-in rule (that I know of) to detect potential cases where a string might be accidentally iterated over instead of being treated as a single value or being split first.
Use Cases
Proposed Rule Details
The rule would detect:
str
The text was updated successfully, but these errors were encountered: