Skip to content

Python ast Module

The python ast module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like.

For example,

  • get decorators of a method
  • get doc string of a class
  • etc...

Get docstring of a class

Python
def get_cls_doc_str(cls_file):
    tree = ast.parse(open(cls_file, 'r').read())
    for part in tree.body:
        if isinstance(part, ast.ClassDef):
            doc = ast.get_docstring(part)
            print(f"doc: {doc}")

Get Decorators of the method inside a class

Python
def get_cls_method_decorators(cls_file):
    tree = ast.parse(open(cls_file, 'r').read())
    for cls in ast.walk(p):
        if not isinstance(cls, ast.ClassDef):
            continue
        cls_name = cls.name
        for method in ast.walk(cls):
            if not isinstance(c, ast.FunctionDef):
                continue
             for dec in m.decorator_list:
                if hasattr(d, 'func'):
                    dec_id = d.func.id
                else:
                    dec_id = d.id
                print(f"cls: {cls_name}, method: {method.name}, decorator: {dec_id}")