Skip to content

Commit 8b665f4

Browse files
authored
Avoid parenthesizing octal/hex or binary literals in object positions (#8160)
1 parent 84979f9 commit 8b665f4

File tree

2 files changed

+27
-116
lines changed

2 files changed

+27
-116
lines changed

crates/ruff_python_formatter/src/expression/expr_attribute.rs

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,13 @@ impl FormatNodeRule<ExprAttribute> for FormatExprAttribute {
3838

3939
let format_inner = format_with(|f: &mut PyFormatter| {
4040
let parenthesize_value =
41-
// If the value is an integer, we need to parenthesize it to avoid a syntax error.
42-
matches!(
43-
value.as_ref(),
44-
Expr::Constant(ExprConstant {
45-
value: Constant::Int(_) | Constant::Float(_),
46-
..
47-
})
48-
) || is_expression_parenthesized(value.into(), f.context().comments().ranges(), f.context().source());
41+
is_base_ten_number_literal(value.as_ref(), f.context().source()) || {
42+
is_expression_parenthesized(
43+
value.into(),
44+
f.context().comments().ranges(),
45+
f.context().source(),
46+
)
47+
};
4948

5049
if call_chain_layout == CallChainLayout::Fluent {
5150
if parenthesize_value {
@@ -164,3 +163,23 @@ impl NeedsParentheses for ExprAttribute {
164163
}
165164
}
166165
}
166+
167+
// Non Hex, octal or binary number literals need parentheses to disambiguate the attribute `.` from
168+
// a decimal point. Floating point numbers don't strictly need parentheses but it reads better (rather than 0.0.test()).
169+
fn is_base_ten_number_literal(expr: &Expr, source: &str) -> bool {
170+
if let Some(ExprConstant { value, range }) = expr.as_constant_expr() {
171+
match value {
172+
Constant::Float(_) => true,
173+
Constant::Int(_) => {
174+
let text = &source[*range];
175+
!matches!(
176+
text.as_bytes().get(0..2),
177+
Some([b'0', b'x' | b'X' | b'o' | b'O' | b'b' | b'B'])
178+
)
179+
}
180+
_ => false,
181+
}
182+
} else {
183+
false
184+
}
185+
}

crates/ruff_python_formatter/tests/snapshots/black_compatibility@simple_cases__attribute_access_on_number_literals.py.snap

Lines changed: 0 additions & 108 deletions
This file was deleted.

0 commit comments

Comments
 (0)