Skip to content

ast.unparse: don't insert space before attribute access on bool constants #158237

Description

@Tony123-tech

Lib/_ast_unparse.py's visit_Attribute inserts a space before the "."
when node.value is an int literal, to avoid the syntax error in
3.abs(). But bool is a subclass of int, so True.real and
False.class also get the space:

>>> import ast
>>> ast.unparse(ast.parse("x = True.real"))
'x = True .real'
>>> ast.unparse(ast.parse("x = False.__class__"))
'x = False .__class__'

True.real and False.class are valid without a space, so the
output is not idiomatic. The fix is to exclude bool from the
isinstance check:

if (isinstance(node.value, Constant)
        and isinstance(node.value.value, int)
        and not isinstance(node.value.value, bool)):
    self.write(" ")

I'd like to submit a PR with this fix and a test.

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions