Skip to content

FURB188 fix should be marked unsafe except with known strs #20724

@dscorbett

Description

@dscorbett

Summary

The fix for slice-to-remove-prefix-or-suffix (FURB188) should be marked unsafe unless it is statically known that the full string and its affix are both strs. If it is statically known that they are instances of unrelated classes, the rule should be suppressed. Otherwise, the fix can change the program’s behavior. They have to be exactly str for the fix to be safe, not subclasses of str. Example:

$ cat >furb188.py <<'# EOF'
class Seq:
    def __init__(self, inner):
        self.inner = inner
    def startswith(self, prefix):
        return tuple(self.inner[:len(prefix)]) == tuple(prefix)
    def __getitem__(self, item):
        return type(self)(self.inner[item])
seq = Seq(("1", "2", "3", "4", "5"))
try:
    if seq.startswith("123"):
        seq = seq[3:]
    print(seq.inner)
except AttributeError as e:
    print(e)

text = "12345"
prefix = ("123",)
try:
    if text.startswith(prefix):
        text = text[len(prefix):]
    print(text)
except TypeError as e:
    print(e)
# EOF

$ python furb188.py
('4', '5')
2345

$ ruff --isolated check furb188.py --select FURB188 --fix
Found 2 errors (2 fixed, 0 remaining).

$ python furb188.py
'Seq' object has no attribute 'removeprefix'
removeprefix() argument must be str, not tuple

Version

ruff 0.13.3 (188c0dc 2025-10-02)

Metadata

Metadata

Assignees

No one assigned

    Labels

    fixesRelated to suggested fixes for violations

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions