berkerpeksag / astor

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

accepts ast.If with empty body #173

Closed ikamensh closed 3 years ago

ikamensh commented 4 years ago

astor produces invalid python code if given an ast.If node with empty body.

example:

import ast

module = ast.parse("if x: x = x + 2")
if_node = module.body[0]
if_node.body = []

import astor
print(astor.to_source(module))

Output:

if x:

Expected - Exception or some valid output, e.g.:

if x:
    pass
isidentical commented 4 years ago

If you give a malformed ast, you get a malformed output. Isn't this the expected case? If you want a corrected output, you can extend / replace the source generator class in the to_source calls.

ikamensh commented 4 years ago

@isidentical It's an edge case, and can be handled. Or it can be stated that some assumptions are made about inputs, and outside these assumptions no guarantees are given.

isidentical commented 4 years ago

I dont know if you are familiar with AST, but there are more then one edge cases. Handling all will result with change the actual behavior. Also this will break some promises, e.g the output of 2 different node will be same although they shouldn't be (ast.If([]) vs ast.If([ast.Pass()]))

berkerpeksag commented 3 years ago

Unfortunately, as Batuhan said, we cannot handle all cases in a malformed AST. If this is the only edge case for your own use case, you can subclass SourceGenerator and use it as to_source(..., source_generator_class=YourCustomSourceGenerator).

I'll also tweak documentation to mention that to_source() expects a valid AST tree.

Closing the issue for now. Thank you for your report!

berkerpeksag commented 3 years ago

See also #79.