Parenthesize multi-line attributes in B009 (#7701)

Closes
https://github.com/astral-sh/ruff/issues/7455#issuecomment-1739800901.
This commit is contained in:
Charlie Marsh 2023-09-28 16:59:00 -04:00 committed by GitHub
parent f45281345d
commit 9611f8134f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 1 deletions

View file

@ -60,3 +60,7 @@ assert getattr(func, '_rpc')is True
# Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1732387247
getattr(*foo, "bar")
setattr(*foo, "bar", None)
# Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1739800901
getattr(self.
registration.registry, '__name__')

View file

@ -91,7 +91,8 @@ pub(crate) fn getattr_with_constant(
if matches!(
obj,
Expr::Name(_) | Expr::Attribute(_) | Expr::Subscript(_) | Expr::Call(_)
) {
) && !checker.locator().contains_line_break(obj.range())
{
format!("{}.{}", checker.locator().slice(obj), value)
} else {
// Defensively parenthesize any other expressions. For example, attribute accesses

View file

@ -336,4 +336,22 @@ B009_B010.py:58:8: B009 [*] Do not call `getattr` with a constant attribute valu
60 60 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1732387247
61 61 | getattr(*foo, "bar")
B009_B010.py:65:1: B009 [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access.
|
64 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1739800901
65 | / getattr(self.
66 | | registration.registry, '__name__')
| |_____________________________________^ B009
|
= help: Replace `getattr` with attribute access
Suggested fix
62 62 | setattr(*foo, "bar", None)
63 63 |
64 64 | # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1739800901
65 |-getattr(self.
66 |- registration.registry, '__name__')
65 |+(self.
66 |+ registration.registry).__name__