LibCST: Converting arbitrary nodes to code
Asked Answered
F

1

8

Is it possible to dump an arbitrary LibCST node into Python code? My use case is that I want to extract the code for functions that match a specific naming scheme. I can extract the FunctionDef nodes that I need, but I don't seem to find a way to convert them to code.

Fiorenze answered 26/3, 2020 at 13:4 Comment(0)
R
10

It is possible using the method code_for_node from the Module class.

You use it as follow:

import libcst

function_def = libcst.parse_statement("def hello_world():\n  print('Hello World')")
print(libcst.Module([]).code_for_node(function_def))

and that would generate the output:

def hello_world():
    print('Hello World')

Riddle answered 14/8, 2020 at 23:34 Comment(1)
Thank you for your solution! Note this does not work for every code object within LibCST, for example it does not work on Annotation. However, it does work on the Param object that contains that same Annotation. Here is a full description of this example.Platinic

© 2022 - 2024 — McMap. All rights reserved.