A formatter for Python code that applies consistent formatting rules based on configurable style guidelines
YAPF's style configuration system provides comprehensive control over code formatting through predefined styles, custom configuration files, and programmatic settings. The style system supports hierarchical configuration with local overrides and extensive customization options.
Core functions for getting, setting, and managing formatting styles.
def Get(setting_name):
"""
Get the value of a style setting.
Args:
setting_name (str): Name of the style setting
Returns:
The current value of the setting
"""
def GetOrDefault(setting_name, default_value):
"""
Get a style setting or return default if not set.
Args:
setting_name (str): Name of the style setting
default_value: Value to return if setting doesn't exist
Returns:
Setting value or default_value
"""
def SetGlobalStyle(style):
"""
Set the global style configuration.
Args:
style (dict): Style configuration dictionary
"""
def Help():
"""
Get help information for all style settings.
Returns:
dict: Mapping of style setting names to help strings
"""Create style configurations from various sources.
def CreateStyleFromConfig(style_config):
"""
Create a style configuration from config string or file.
Args:
style_config (str): Style name ('pep8', 'google', 'facebook', 'yapf')
or path to configuration file
Returns:
dict: Style configuration dictionary
Raises:
StyleConfigError: If configuration cannot be loaded
"""from yapf.yapflib import style
from yapf.yapflib.yapf_api import FormatCode
# Set PEP 8 style globally
pep8_style = style.CreateStyleFromConfig('pep8')
style.SetGlobalStyle(pep8_style)
# Format with Google style
code = "x=[1,2,3]"
formatted, _ = FormatCode(code, style_config='google')
# Format with Facebook style
formatted, _ = FormatCode(code, style_config='facebook')
# Format with YAPF default style
formatted, _ = FormatCode(code, style_config='yapf')from yapf.yapflib import style
# Create and set a custom style
custom_style = style.CreateStyleFromConfig('pep8')
style.SetGlobalStyle(custom_style)
# Get current setting values
indent_width = style.Get('INDENT_WIDTH')
column_limit = style.Get('COLUMN_LIMIT')
print(f"Indent: {indent_width}, Column limit: {column_limit}")
# Get setting with default
use_tabs = style.GetOrDefault('USE_TABS', False)
# Get help for all settings
help_info = style.Help()
for setting, description in help_info.items():
print(f"{setting}: {description}")YAPF supports multiple configuration file formats:
[style]
based_on_style = pep8
column_limit = 100
indent_width = 4
split_before_logical_operator = true[tool.yapf]
based_on_style = "pep8"
column_limit = 100
indent_width = 4
split_before_logical_operator = true[yapf]
based_on_style = pep8
column_limit = 100
indent_width = 4
split_before_logical_operator = truefrom yapf.yapflib import style
# Load from file
custom_style = style.CreateStyleFromConfig('/path/to/.style.yapf')
style.SetGlobalStyle(custom_style)
# Load from pyproject.toml
custom_style = style.CreateStyleFromConfig('/path/to/pyproject.toml')
style.SetGlobalStyle(custom_style)# Common indentation settings
style_config = {
'INDENT_WIDTH': 4, # Number of spaces per indent level
'USE_TABS': False, # Use tabs instead of spaces
'CONTINUATION_INDENT_WIDTH': 4, # Indent for line continuations
'INDENT_CLOSING_BRACKETS': False, # Indent closing brackets
}# Line length settings
style_config = {
'COLUMN_LIMIT': 79, # Maximum line length
'SPLIT_BEFORE_LOGICAL_OPERATOR': True, # Split before logical operators
'SPLIT_BEFORE_ARITHMETIC_OPERATOR': False, # Split before arithmetic operators
'ALLOW_SPLIT_BEFORE_DICT_VALUE': True, # Allow split before dict values
}# Alignment settings
style_config = {
'ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT': True,
'ALLOW_MULTILINE_LAMBDAS': False,
'ALLOW_MULTILINE_DICTIONARY_KEYS': False,
'ARITHMETIC_PRECEDENCE_INDICATION': False,
}Based on the official Python style guide (PEP 8).
formatted, _ = FormatCode(code, style_config='pep8')Based on Google's Python style guide.
formatted, _ = FormatCode(code, style_config='google')Key differences from PEP 8:
Based on Facebook's internal Python style guide.
formatted, _ = FormatCode(code, style_config='facebook')YAPF's own default style.
formatted, _ = FormatCode(code, style_config='yapf')YAPF searches for configuration in this order:
--style parameter.style.yapf in current directory or parent directoriespyproject.toml with [tool.yapf] sectionsetup.cfg with [yapf] sectionfrom yapf.yapflib import file_resources
# Get default style for a directory
style_config = file_resources.GetDefaultStyleForDir('/path/to/project')
# This searches up the directory tree for configuration filesclass StyleConfigError(YapfError):
"""Raised when there's a problem reading the style configuration."""Example error handling:
from yapf.yapflib import style
from yapf.yapflib.errors import StyleConfigError
try:
custom_style = style.CreateStyleFromConfig('/path/to/invalid/config')
except StyleConfigError as e:
print(f"Style configuration error: {e}")Disable YAPF formatting for specific sections:
# yapf: disable
poorly_formatted = {
'key': 'value',
'other': 'data'
}
# yapf: enableOr using fmt comments:
# fmt: off
poorly_formatted = {
'key': 'value',
'other': 'data'
}
# fmt: on# .pre-commit-config.yaml
repos:
- repo: https://github.com/google/yapf
rev: v0.43.0
hooks:
- id: yapf
args: [--style=google]Create reusable style configurations:
# my_team_style.py
from yapf.yapflib import style
TEAM_STYLE = {
'based_on_style': 'pep8',
'column_limit': 100,
'indent_width': 4,
'split_before_logical_operator': True,
'spaces_around_power_operator': True,
}
def apply_team_style():
"""Apply team-specific formatting style."""
style.SetGlobalStyle(TEAM_STYLE)Install with Tessl CLI
npx tessl i tessl/pypi-yapf