Skip to content

Commit 9def455

Browse files
authored
gh-158237: Don't insert space before attribute access on bool constants (#158238)
1 parent 7952713 commit 9def455

3 files changed

Lines changed: 16 additions & 1 deletion

File tree

‎Lib/_ast_unparse.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -925,7 +925,11 @@ def visit_Attribute(self, node):
925925
# Special case: 3.__abs__() is a syntax error, so if node.value
926926
# is an integer literal then we need to either parenthesize
927927
# it or add an extra space to get 3 .__abs__().
928-
if isinstance(node.value, Constant) and isinstance(node.value.value, int):
928+
# bool is a subclass of int, but True.real and False.real are
929+
# valid without a space.
930+
if (isinstance(node.value, Constant)
931+
and isinstance(node.value.value, int)
932+
and not isinstance(node.value.value, bool)):
929933
self.write(" ")
930934
self.write(".")
931935
self.write(node.attr)

‎Lib/test/test_unparse.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,14 @@ def test_unary_parens(self):
335335
def test_integer_parens(self):
336336
self.check_ast_roundtrip("3 .__abs__()")
337337

338+
def test_attribute_on_bool(self):
339+
# gh-158237: True.real should not gain a space
340+
self.check_src_roundtrip("x = True.real")
341+
self.check_src_roundtrip("x = False.__class__")
342+
343+
def test_attribute_on_int_still_spaced(self):
344+
self.check_src_roundtrip("x = 3 .__abs__()")
345+
338346
def test_huge_float(self):
339347
self.check_ast_roundtrip("1e1000")
340348
self.check_ast_roundtrip("-1e1000")
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :func:`ast.unparse` to not insert a space before attribute
2+
access on bool constants (e.g. ``True.real`` instead of
3+
``True .real``).

0 commit comments

Comments
 (0)