r/Python • • 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

14 comments sorted by

View all comments

1

u/RomfordNavy Oct 30 '26

Thanks for the suggestion u/michallandry62 but looks like Parso doesn't support 3.15 yet.

u/Wurstinator thanks for proving that libcast wouild install if I had a C compiler instaled. Was just about to install that but before I did was now considering whether libCST is actually the correct tool for what I want to do.

u/AleDev99 It's primary job is to modify source code and as part of that process one of it's tasks is to replace a holder, say '#replaceThis' with a block of code. I am now trying to establish whether libCST will allow that sort of replacement or whether that needs to be done a separate parse first.

2

u/Nanotheslayer 25d ago

If the markers are standalone comment lines in otherwise valid Python, I'd build on the tokenize suggestion: identify COMMENT tokens, then replace the corresponding source lines. That avoids treating '#replaceThis' inside a triple-quoted string as a placeholder. Keep the marker line's indentation when inserting the block, and apply multiple edits from the bottom up so earlier coordinates stay valid. I'd check a marker inside a string, one in a nested block, and one at EOF before wiring it into the rest of your edits. LibCST still makes sense for the structural changes beyond that.

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.