Search code examples
pythonabstract-syntax-tree

Python AST : Insert argument to class


Using AST to add argument to the existing class. In the AST world, it is classdef which I already found, how do I add an argument to that classDef or update the bases basically ?

From

class testApp:

To

class testApp(Core):

Solution

  • On Python 3.9 you have ast.unparse available, which allows you to do this:

    import ast
    ast_obj = ast.parse("class testApp:\n  pass")
    ast_obj.body[0].bases.append(ast.Name(id='Core'))
    print(ast.unparse(ast_obj))