YAPF - Yet Another Python Formatter
YAPF (Yet Another Python Formatter) is an opinionated code formatter for Python, developed by Google. It automatically re-formats Python code to conform to the PEP 8 style guide and other configurable style conventions, aiming to improve code readability and consistency. The current version is 0.43.0, and it generally follows a stable release cadence with updates for Python version support and bug fixes.
Warnings
- breaking Python 3.6 support was dropped in YAPF version 0.37.0. Subsequent versions (including 0.43.0) require Python 3.7 or newer.
- gotcha For CLI usage, files are not modified in-place by default. If you run `yapf file.py`, it will print the formatted code to stdout but leave the original file untouched.
- gotcha Configuration for programmatic use (e.g., `FormatCode`) does not automatically discover `.style.yapf` or `pyproject.toml` files from the current working directory. You must explicitly pass `style_config` or other parameters.
- gotcha Internal AST representation changed from `pytree` to `libcst` in version 0.40.0. While this is primarily an internal refactoring, users who relied on direct interaction with YAPF's internal AST objects might experience compatibility issues.
Install
-
pip install yapf
Imports
- FormatCode
from yapf.yapf_api import FormatCode
Quickstart
from yapf.yapf_api import FormatCode
unformatted_code = """
def example_function( arg1, arg2 = None ):
if arg1 :
print( "Hello", arg1 )
else:
return arg2
"""
formatted_code, changed = FormatCode(unformatted_code)
print("--- Original ---")
print(unformatted_code)
print("\n--- Formatted ---")
print(formatted_code)
print(f"\nChanged: {changed}")
# You can also pass style parameters
formatted_code_google, _ = FormatCode(unformatted_code, style_config='google')
print("\n--- Formatted (Google Style) ---")
print(formatted_code_google)