Kausthubh J Rao
  • Blog

© 2025 Kausthubh

Back

Black - Python Code Formatter Contribution

2025

PythonOpen SourceCode FormatterPython 3.12CompilerAST
Black - Python Code Formatter Contribution
Contributed a fix to Black, the uncompromising Python code formatter, resolving formatting issues with Python 3.12's new generics syntax. The fix ensures proper handling of type parameters when function parameters contain trailing commas.
Identified and fixed a bug in Black's formatting engine where functions with type parameters and trailing commas in their parameter lists were incorrectly formatted. The issue occurred in the `left_hand_split()` function, which processes both square brackets (for type parameters) and parentheses (for function parameters) as potential split points. When a trailing comma forced a split, the algorithm would incorrectly choose type parameter brackets instead of function parameter parentheses, causing malformed output. The solution involved modifying the split logic to avoid selecting parentheses as split points when they occur inside type parameter brackets, ensuring type parameters stay on the head line while the split correctly happens at the function parameter list. This contribution was merged into Black's main branch and is now used by millions of Python developers worldwide.

Key Features

  • Fixed Python 3.12 generics syntax formatting bug
  • Improved type parameter expansion logic in left_hand_split()
  • Correct handling of trailing commas in function parameters with type parameters
  • Maintained backward compatibility with existing code
  • Added comprehensive test cases for edge cases
  • Contributed to one of the most widely-used Python tools (41.2k+ stars)

Technology Stack

Backend

PythonASTCode Parsing

Tools

GitpytestBlack Codebase

Challenges

  • Understanding Black's complex AST-based formatting algorithm
  • Identifying the root cause in the left_hand_split() function
  • Ensuring the fix doesn't break existing formatting behavior
  • Writing test cases that cover all edge cases
  • Navigating the contribution workflow of a major open-source project

Key Learnings

  • Deep understanding of Python AST manipulation and code formatting
  • Working with large-scale open-source codebases
  • Writing robust test cases for formatter edge cases
  • Contributing to projects with strict code quality standards
  • Understanding Python 3.12's new generics syntax
  • Code review process in major OSS projects
GitHub Documentation

Achievements

  • Merged into Black main branch
  • Fixed issue #4740
  • Used by 41.2k+ developers