berkerpeksag / astor

Python AST read/write
https://pypi.org/project/astor/
BSD 3-Clause "New" or "Revised" License
810 stars 102 forks source link

astor.to_source(tree_from_ast) generate different source code on identical node #132

Open free2dog opened 5 years ago

free2dog commented 5 years ago

Same ast node in memory.

expected output source code(arguments list omitted):

def make_mocked_request(
    ) ->Any:
    mock.Mock = annotations.annot_aiohttp_test_utils_make_mocked_request_mock_Mock()

actually I got parentheses around the _ast.Call:

def make_mocked_request(
    ) ->Any:
    mock.Mock = (annotations.
        annot_aiohttp_test_utils_make_mocked_request_mock_Mock())

when I use debugger to print source using astor.to_source() on this specific _ast.Assign node,

I use these in my debugger console

import astor astor.to_source(fundefNode.body[0])

I got the correct version

mock.Mock = annotations.annot_aiohttp_test_utils_make_mocked_request_mock_Mock(\n )\n

But when I print all functionDef node,

astor.to_source(fundefNode)

I got the wrong version

... mock.Mock = (annotations.\n annot_aiohttp_test_utils_make_mocked_request_mock_Mock())\n ...

berkerpeksag commented 5 years ago

Thank you for your report! I think #75 was meant to fix cases like this. I will work on that after we release 0.8 next month.

rvprasad commented 4 years ago

The statement mock.Mock = annotations.annot_aiohttp_test_utils_make_mocked_request_mock_Mock() is exactly 80 chars without indentation. Hence, astor.to_source(fundefNode.body[0]) output meets @bryce-ma's expectation.

With indentation of 4 spaces, the same statement is 84 chars. Hence, the line is broken and, instead of adding a line continuation character ('\'), the pretty printer wraps the rhs expression in parenthesis.

So, I think the perceived "incorrectness" of the breaks is due to the length of the statement when used in isolation and when used inside a function.

That said, to help users, astor should commit to either use of parenthesis or use of line continuation or be explicit about when would each be supported.