-
I'm trying to find a solution to match and manipulate a combination of python commands/libcst.nodes from a file / module example: x = 1
bar: int
"literal docstring" I would like to identify/extract/manipulate the pair(s) of lines that contain an Assign or AnnAssign followed by a docstring
import libcst as cst
import libcst.matchers as m
source = """\
x = 1
bar: int
"literal docstring"
"""
module = cst.parse_module(source)
# Matcher for (a module with)
# - an assignment or Annonated asignment of a literal
# - a docstring
literal_aa_matcher = m.Module( body= [
m.ZeroOrMore(),
m.SimpleStatementLine(body= [m.AnnAssign(),]),
m.SimpleStatementLine(
body= [m.Expr( value=m.SimpleString()),]
),
m.ZeroOrMore(),
])
# try to match
m.matches(module, literal_aa_matcher)
#>> match returns True
m.findall(module, literal_aa_matcher)
#>> find returns the entire module , not usefull
m.extract(module, literal_aa_matcher)
#>> returns {}
m.extractall(module, literal_aa_matcher)
#>> returns [{}] I have tried many combinations including to try to match two (or more) consecutive nodes, Matching directly on the body sequence or children of the module does not seem to work either. Any suggestions appreceated |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Maybe this is doable with the matcher API, but I'd personally just implement |
Beta Was this translation helpful? Give feedback.
-
Yeah your option 2 sounds good too, probably better if you wanna change the first node. |
Beta Was this translation helpful? Give feedback.
Yeah your option 2 sounds good too, probably better if you wanna change the first node.
Keep in mind that string node will be wrapped in at least one statement node in the body sequence