berkerpeksag / astor

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

Add Comment node (for code generation purposes) #50

Open inklesspen opened 8 years ago

inklesspen commented 8 years ago

Although the AST does not include a Comment node, it is frequently a good idea to insert comments into generated code. It's possible to wrap textual comments in a string instead, but it doesn't look as nice.

I've been experimenting and it looks like it should be feasible to add a custom Comment node (inheriting from ast.Expr, possibly).

The really interesting bit is when you allow the Comment's value to be not just strings, but other AST nodes. In this case you could generate syntactically-valid and properly indented commented-out code.

I've got this working for single line statements and I think I can do it for multiple line blocks like function definitions as well. However, before I go further I want to be sure something like this would be accepted into the project.

pmaupin commented 8 years ago

Sounds like an awesome idea to me!

berkerpeksag commented 8 years ago

+1! Please send a pull request :)

pmaupin commented 7 years ago

Closing for now; anyone who really wants the comments is welcome to re-open and work on the pull.

berkerpeksag commented 7 years ago

I think this should be left open. There might be someone out there who are looking for an issue to contribute to an open source project and it's not easy to find closed issues on GitHub.

pmaupin commented 7 years ago

I've added an example of how to do this in PR #75. So we should possibly document it, but I think the code is done.

mathben commented 2 years ago

The solution seems here : https://github.com/berkerpeksag/astor/pull/75/commits/4a152b8c90db1634cb86c83601870ee6aa84e6c0