r/Python • u/RomfordNavy • Oct 29 '26
Discussion Alternative to libCST
Looking for a suggestion of an alternative CST parser to libcst. Have been trying to install libcst for over two days now but still unable to do so, I think the issue might be that there is no PyYaml `wheel` for Python 3.15.
So now wondering if there might be some other alternative CST parser available. I need to parse comments as well as other code so standard AST won't work as far as I know.
15
Upvotes
View all comments
Show parent comment
1
u/AleDev99 Oct 30 '26
Yes, libCST can do it in one pass, no separate parse needed. A comment on its own line is kept as an EmptyLine in the leading_lines of the next statement, so a CSTTransformer can catch it there. In leave_SimpleStatementLine / leave_Compound statements (or a generic on_leave for any statement node), check whether any leading_lines comment equals "#replaceThis"; if so, drop that line and return cst.FlattenSentinel([*cst.parse_module(snippet).body, updated_node]), so your new block lands right before that statement with the indentation handled for you. One catch: if the placeholder is the last thing in a block, there's no next statement, so it ends up in the block's footer instead. Honestly, if the placeholder is always on its own line, a plain text replace that keeps the line's indentation is the simplest fix, and you only need libCST for the rest of the edits.