[New-bugs-announce] [issue44142] ast.unparse: visually better code generation

Batuhan Taskaya report at bugs.python.org
Sat May 15 09:29:46 EDT 2021


New submission from Batuhan Taskaya <isidentical at gmail.com>:

This issue is for tracking possible places where we could generate better code on ast.unparse (better as in more closely to what people are actually writing than our naive implementation). 

Examples;
>>> import ast
>>> ast.unparse(ast.parse('a, b, c = [1,2,3]'))
'(a, b, c) = [1, 2, 3]'

could be
>>> ast.unparse(ast.parse('a, b, c = [1,2,3]'))
'a, b, c = [1, 2, 3]'

OR
>>> print(ast.unparse(ast.parse('if value := d.get("something"): print(value)')))
if (value := d.get('something')):
    print(value)

could be
>>> print(ast.unparse(ast.parse('if value := d.get("something"): print(value)')))
if value := d.get('something'):
    print(value)

We could even go further with the long line unpacking (which would definitely require some sort of clever algorithm for nested structures). 

>>> source = '[\n' + '\tsomething,\n' * 20 + ']'
>>> print(source)
[
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
        something,
]
>>> print(ast.unparse(ast.parse(source)))
[something, something, something, something, something, something, something, something, something, something, something, something, something, something, something, something, something, something, something, something]

----------
assignee: BTaskaya
components: Library (Lib)
messages: 393714
nosy: BTaskaya, pablogsal
priority: normal
severity: normal
status: open
title: ast.unparse: visually better code generation
type: enhancement
versions: Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44142>
_______________________________________


More information about the New-bugs-announce mailing list