Is there a decode function in libcst to convert a tree to python source code?

138 views Asked by At

I got a piece of output from a sample libcst.parse_module program like:

Module(
    body=[
        SimpleStatementLine(
            body=[
                Assign(
                    targets=[
                        AssignTarget(
                            target=Name(
                                value='hi',
                                lpar=[],
                                rpar=[],
                            ),
                            whitespace_before_equal=SimpleWhitespace(
                                value=' ',
                            ),
                            whitespace_after_equal=SimpleWhitespace(
                                value=' ',
                            ),
                        ),
                    ],
                    value=Integer(
                        value='0',
                        lpar=[],
                        rpar=[],
                    ),
                    semicolon=MaybeSentinel.DEFAULT,
                ),
            ],
            leading_lines=[],
            trailing_whitespace=TrailingWhitespace(
                whitespace=SimpleWhitespace(
                    value='',
                ),
                comment=None,
                newline=Newline(
                    value=None,
                ),
            ),
        ),
    ],
    header=[],
    footer=[],
    encoding='utf-8',
    default_indent='    ',
    default_newline='\n',
    has_trailing_newline=False,
)

I search a lot but still don't know how to decode this cst tree back to python source code. Can anyone help?

I have read this document libcst but there was only the tutorial to encode python source code into cst tree using parse_module. Can't find the way to decode cst tree back to python source code.

1

There are 1 answers

0
hoefling On

That's what Module.code does. Your example, revisited:

In [1]: from libcst import *

In [2]: m = Module(
   ...:     body=[
   ...:         Assign(
                ...
   ...:     has_trailing_newline=False,
   ...: )

In [3]: m.code
Out[3]: 'hi = 0'

For arbitrary nodes, use the method Module.code_for_node(). Example:

In [4]: n = SimpleString(value='"spam"')

In [5]: m.code_for_node(n)
Out[5]: '"spam"'

If you have no Module instance available, create one yourself using libcst.parse_module(). Example:

In [6]: n = Integer(value='42')

In [7]: parse_module('').code_for_node(n)
Out[7]: '42'