Skip to content

contains_effect should consider f-strings to have effects #12953

@dscorbett

Description

@dscorbett

contains_effect should consider f-strings to have effects because of the implicit __str__ or __repr__ call. This affects any rule that relies on contains_effect; here is an example with RUF019.

$ ruff --version
ruff 0.6.1
$ cat ruf019.py
class C:
    def __init__(self):
        self.i = 0

    def __str__(self):
        self.i += 1
        return str(self.i)


if __name__ == "__main__":
    c = C()
    dct = {"1": "a", "2": "b"}
    if f"{c}" in dct and dct[f"{c}"]:
        pass
    print(c.i)
$ python ruf019.py
2
$ ruff check --isolated --select RUF019 ruf019.py --fix
Found 1 error (1 fixed, 0 remaining).
$ python ruf019.py
1

Some f-strings can be statically proven to not have effects, if they contain no formatted expressions (f"x") or they only format values of types formatting which is known not to have effects (f"{1}").

Metadata

Metadata

Labels

help wantedContributions especially welcome

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions