A formatter for Python code that applies consistent formatting rules based on configurable style guidelines
npx @tessl/cli install tessl/pypi-yapf@0.43.0YAPF (Yet Another Python Formatter) is a Python code formatter that applies consistent formatting rules to Python source code. Based on the algorithm from clang-format, YAPF looks at code as a series of "unwrappable lines" and uses a priority queue to determine the best formatting with minimal penalty. Unlike tools that just fix style guide violations, YAPF considers the entire module to make holistic formatting decisions.
pip install yapf# Core formatting API
from yapf.yapflib.yapf_api import FormatCode, FormatFile, FormatTree, FormatAST, ReadFile
# Style configuration
from yapf.yapflib import style
from yapf.yapflib.style import StyleConfigError
# File operations
from yapf.yapflib import file_resources
# Error handling
from yapf.yapflib.errors import YapfError, FormatErrorMsg
# Command line interface
import yapffrom yapf.yapflib.yapf_api import FormatCode
# Format a string of Python code
unformatted_code = '''
def hello(name):
print("Hello, "+name+"!")
'''
formatted_code, changed = FormatCode(unformatted_code)
print(formatted_code)
# Output:
# def hello(name):
# print("Hello, " + name + "!")
# Format with specific style
formatted_code, changed = FormatCode(
unformatted_code,
style_config='google'
)
# Format a file
from yapf.yapflib.yapf_api import FormatFile
result, encoding, changed = FormatFile('my_script.py')Command line usage:
# Format a file in place
yapf -i my_script.py
# Format and show diff
yapf -d my_script.py
# Format with specific style
yapf --style=google my_script.py
# Format recursively
yapf -r -i my_project/YAPF's architecture is built around several key components:
This design allows YAPF to make sophisticated formatting decisions while maintaining configurability through style settings.
Primary functions for formatting Python code, including string formatting, file formatting, and tree-based formatting with configurable styles and line-specific formatting options.
def FormatCode(unformatted_source, filename='<unknown>', style_config=None, lines=None, print_diff=False):
"""
Format a string of Python code.
Args:
unformatted_source (str): The code to format
filename (str): Name of file being reformatted
style_config (str): Style name or file path
lines (list): List of (start, end) line ranges to format
print_diff (bool): Return diff instead of formatted code
Returns:
tuple: (reformatted_source, changed)
"""
def FormatFile(filename, style_config=None, lines=None, print_diff=False, in_place=False, logger=None):
"""
Format a single Python file.
Args:
filename (str): File to reformat
style_config (str): Style name or file path
lines (list): List of (start, end) line ranges to format
print_diff (bool): Return diff instead of formatted code
in_place (bool): Write reformatted code back to file
logger: Stream for logging output
Returns:
tuple: (reformatted_code, encoding, changed)
"""
def FormatTree(tree, style_config=None, lines=None):
"""
Format a parsed lib2to3 pytree.
Args:
tree: Root of pytree to format
style_config (str): Style name or file path
lines (list): List of (start, end) line ranges to format
Returns:
str: Formatted source code
"""Comprehensive style configuration system supporting predefined styles (PEP8, Google, Facebook) and custom configurations through files or programmatic settings.
def Get(setting_name):
"""Get a style setting value."""
def SetGlobalStyle(style):
"""Set global style configuration."""
def CreateStyleFromConfig(style_config):
"""Create style from config string or file."""
def Help():
"""Return dict mapping style names to help strings."""File handling utilities for reading Python files with proper encoding detection, writing formatted code, and managing configuration files and exclude patterns.
def ReadFile(filename, logger=None):
"""
Read file contents with encoding detection.
Args:
filename (str): Name of file to read
logger: Function for logging messages
Returns:
tuple: (source, line_ending, encoding)
"""Complete command-line interface supporting file formatting, directory recursion, parallel processing, and various output modes including in-place editing and diff generation.
def main(argv):
"""
Main command-line entry point.
Args:
argv (list): Command-line arguments including program name
Returns:
int: Exit code (0 for success)
"""
def FormatFiles(filenames, lines, style_config=None, no_local_style=False,
in_place=False, print_diff=False, parallel=False,
quiet=False, verbose=False, print_modified=False):
"""
Format multiple files with various options.
Args:
filenames (list): List of files to reformat
lines (list): List of (start, end) line ranges
style_config (str): Style name or file path
no_local_style (bool): Don't search for local style config
in_place (bool): Modify files in place
print_diff (bool): Show diff instead of formatted code
parallel (bool): Use parallel processing
quiet (bool): Suppress output
verbose (bool): Show filenames while processing
print_modified (bool): Show names of modified files
Returns:
bool: True if any source code changed
"""class YapfError(Exception):
"""Base exception class for YAPF errors."""
class StyleConfigError(YapfError):
"""Raised when there's a problem reading the style configuration."""# Regex patterns for controlling YAPF formatting
DISABLE_PATTERN = r'^#.*\b(?:yapf:\s*disable|fmt: ?off)\b'
ENABLE_PATTERN = r'^#.*\b(?:yapf:\s*enable|fmt: ?on)\b'def FormatErrorMsg(e):
"""
Convert an exception into a standard format.
The standard error message format is:
<filename>:<lineno>:<column>: <msg>
Args:
e: An exception
Returns:
str: A properly formatted error message string
"""