Hello.
I have some Python source code that I am trying to modify using LibCST
. In short, I need to import 3 modules into the source .py file at a specific location. I am using LibCST
instead of AST
because I need to preserve comments and whitespaces. Examples are provided below of what I'm trying to achieve.
I've read the documentation and tried to utilize their examples but I cannot wrap my head around it. Any help at all is greatly appreciated!
Source File
import car
import horse
import cheese
x = 1
Modified Source File
import car
import horse
import cheese
import new
import packages
x = 1
How do I use LibCST ?
1. Check the "end result" CST
You can do this using
libcst.tool.dump
, which displays the CST.Output:
It's just like reading code, to avoid getting lost I just focus on the important things:
It's a Python file (
Module
),which contains a couple of lines (
SimpleStatementLine
),some contain imports (
ImportAlias
), with package names (Name=...
),and the last line contains an assignment and other stuff we don't care about.
2. Write a code transformer
Documentation: How to transform code using libcst - tutorial
The easiest way to add code is by recognizing a code pattern where code needs to be inserted. For instance, if code needs to be inserted after
import cheese
statements: in the transformer, code is inserted when visiting aSimpleStatementLine
, containing anImportAlias
whichName
is "cheese".You can use Python 3.10's structural pattern matching.
3. And finally
Output: