3

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.

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this only works if the list elements have a parsable representation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.