CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-yapf

A formatter for Python code that applies consistent formatting rules based on configurable style guidelines

Overview
Eval results
Files

style-configuration.mddocs/

Style Configuration

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.

Capabilities

Style Management

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
    """

Style Creation

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
    """

Usage Examples

Using Predefined Styles

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')

Working with Style Settings

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}")

Custom Configuration Files

YAPF supports multiple configuration file formats:

.style.yapf file

[style]
based_on_style = pep8
column_limit = 100
indent_width = 4
split_before_logical_operator = true

pyproject.toml configuration

[tool.yapf]
based_on_style = "pep8"
column_limit = 100
indent_width = 4
split_before_logical_operator = true

setup.cfg configuration

[yapf]
based_on_style = pep8
column_limit = 100
indent_width = 4
split_before_logical_operator = true

Loading Custom Configurations

from 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)

Key Style Settings

Indentation and Spacing

# 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 and Breaking

# 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 and Formatting

# Alignment settings
style_config = {
    'ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT': True,
    'ALLOW_MULTILINE_LAMBDAS': False,
    'ALLOW_MULTILINE_DICTIONARY_KEYS': False,
    'ARITHMETIC_PRECEDENCE_INDICATION': False,
}

Predefined Styles

PEP 8 Style

Based on the official Python style guide (PEP 8).

formatted, _ = FormatCode(code, style_config='pep8')

Google Style

Based on Google's Python style guide.

formatted, _ = FormatCode(code, style_config='google')

Key differences from PEP 8:

  • 4-space hanging indents
  • Spaces around default parameter values
  • Different line continuation rules

Facebook Style

Based on Facebook's internal Python style guide.

formatted, _ = FormatCode(code, style_config='facebook')

YAPF Style

YAPF's own default style.

formatted, _ = FormatCode(code, style_config='yapf')

Style Configuration Hierarchy

YAPF searches for configuration in this order:

  1. Command line --style parameter
  2. .style.yapf in current directory or parent directories
  3. pyproject.toml with [tool.yapf] section
  4. setup.cfg with [yapf] section
  5. Default style (PEP 8)

Programmatic Style Discovery

from 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 files

Error Handling

class 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}")

Advanced Configuration

Conditional Formatting

Disable YAPF formatting for specific sections:

# yapf: disable
poorly_formatted = {
    'key':    'value',
    'other':  'data'
}
# yapf: enable

Or using fmt comments:

# fmt: off
poorly_formatted = {
    'key':    'value', 
    'other':  'data'
}
# fmt: on

Integration with Pre-commit

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/google/yapf
    rev: v0.43.0
    hooks:
      - id: yapf
        args: [--style=google]

Custom Style Templates

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

docs

command-line.md

core-formatting.md

file-operations.md

index.md

style-configuration.md

tile.json