Reformating your code without AI - let's see how a formatter works

By Cheuk Ting Ho

Elevator Pitch

We don’t need AI for writing better code! Formators like Black and PyBetter have been automatically refactoring messy code way before AI agents claim to help you write codes. In this talk, we are going to explore how formatters analyse and manipulate the CST of your code to make it nicer.

Description

Recently year there are AI agents that pops up in the market saying that they can help you to write code. However, there are tools out there that have been used over decades that can help us write better codes - the auto formats like Black and PyBetter that can refactor your code into nicer-looking ones. In this talk, we are going to explore how auto-formatters analyse and manipulate the CST of your code to make it nicer.

First, we will introduce what is an Abstract Syntax Tree (AST) and a Concrete Syntax Tree (CST). Next, we will talk about libcst and how it analyses the code and express the CST of your code as Python objects. Then, we explore how we can use the match method provided and modify our code if the logic matches. By the end of it, the auto-formatters would not be a mystery for the audience anymore as we now understand the inner working of it.

This talk is for intermediate-level Python coders who are curious about how auto-formatter works and learn about Concrete Syntax Tree.

Outline

  • Introduction: What is AST and what is CST, what are the differences (5 mins)
  • Introducing libcst: example codes (5 mins)
  • Matching CST patterns: example of doing it with libcst 5 mins)
  • How auto-formatter works (10 mins)
  • Conclusions (5 mins)