Reformating your code without AI - let's see how a formatter works
summary
Explains how autoformatters parse and rewrite Python using a concrete syntax tree via libcst, showing that CST retains whitespace, comments and commas so formatters can change layout reliably. Demonstrates using match/matcher patterns and a Transformer to traverse the huge CST, flip boolean literals across a module, and emit updated source with the .code attribute. Works on small examples; live CST outputs very large trees and is practical for prototyping though heavy for massive codebases.
AI-written summary · about
chapters (20)
- 0:00Introduction and self-introduction
- 1:52Why use code formatters
- 2:54Understanding Python AST basics
- 4:40Abstract vs concrete syntax trees
- 8:11Why formatters need CST details
- 10:16Introducing libCST for formatting
- 13:26Matching patterns with libCST
- 15:12Visitors for tree traversal
- 17:18Example of visitor pattern
- 18:22Collecting typing annotations
- 20:27Transformers for code modification
- 21:11Visitors vs Transformers
- 21:53Typing Transformer example
- 23:37Generating source code from AST
- 24:19Building a Boolean inverter Transformer
- 25:22Flipping true and false values
- 26:46Benefits of custom Transformers
- 27:07Conclusion and key takeaways
- 27:49OpenSSF event announcement
- 28:51Q&A on libCST and formatters
