pythonparsingabstract-syntax-tree

How to convert Python List into ast.List?


How can I convert Python object - a list, into an ast.List object, so I can appent it to the main AST tree as a node

    huge_list [ 1, "ABC", 4.5 ]

    object = ast.Assign([ast.Name(huge_list_name, ast.Store())], (ast.List(huge_list, ast.Load())))
    object.lineno = None

    result = ast.unparse(object)
    print(result)

    tree.body.append(object)

but it fails while parsing each field from the sample list.


Solution

  • Assuming your list is made up of simple objects like strings and numbers, you can parse its representation back into an ast.Module, then dig the ast.List out of the module body:

    >>> huge_list = [1, "ABC", 4.5]
    >>> mod = ast.parse(repr(huge_list))
    >>> [expr] = mod.body
    >>> expr.value
    <ast.List at 0x7fffed231190>