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

core-formatting.mddocs/

Core Formatting API

The core formatting API provides the primary functions for formatting Python code. These functions handle string formatting, file formatting, and tree-based formatting with configurable styles and selective line formatting.

Capabilities

String Formatting

Format Python code provided as a string, with options for custom styles, selective line formatting, and diff output.

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 (default: '<unknown>')
        style_config (str): Either a style name ('pep8', 'google', 'facebook') or path to style file
        lines (list): List of (start, end) tuples for line ranges to format (1-indexed)
        print_diff (bool): Return unified diff instead of formatted code
        
    Returns:
        tuple: (reformatted_source, changed)
            - reformatted_source (str): Formatted code or diff if print_diff=True
            - changed (bool): True if source was modified
    """

Usage examples:

from yapf.yapflib.yapf_api import FormatCode

# Basic formatting
code = "x=[1,2,3]\nprint(x)"
formatted, changed = FormatCode(code)
print(formatted)
# x = [1, 2, 3]
# print(x)

# Format with Google style
formatted, changed = FormatCode(code, style_config='google')

# Format specific lines only
formatted, changed = FormatCode(code, lines=[(1, 1)])  # Format only first line

# Get diff instead of formatted code
diff, changed = FormatCode(code, print_diff=True)
print(diff)  # Shows unified diff

File Formatting

Format Python files directly from the filesystem with automatic encoding detection and optional in-place editing.

def FormatFile(filename, style_config=None, lines=None, print_diff=False, in_place=False, logger=None):
    """
    Format a single Python file.
    
    Args:
        filename (str): Path to file to reformat
        style_config (str): Either a style name or path to style file
        lines (list): List of (start, end) tuples for line ranges to format (1-indexed)
        print_diff (bool): Return diff instead of formatted code
        in_place (bool): Write reformatted code back to the file
        logger: Function to call for logging (e.g., logging.warning)
        
    Returns:
        tuple: (reformatted_code, encoding, changed)
            - reformatted_code (str): Formatted code (None if in_place=True)
            - encoding (str): File encoding detected
            - changed (bool): True if file was modified
            
    Raises:
        IOError: If there was an error reading the file
        ValueError: If both in_place and print_diff are True
    """

Usage examples:

from yapf.yapflib.yapf_api import FormatFile

# Format file and return result
result, encoding, changed = FormatFile('my_script.py')
if changed:
    print("File was reformatted")
    print(result)

# Format file in place
_, encoding, changed = FormatFile('my_script.py', in_place=True)

# Get diff of changes
diff, encoding, changed = FormatFile('my_script.py', print_diff=True)

# Format with custom style and logging
import logging
result, encoding, changed = FormatFile(
    'my_script.py',
    style_config='google',
    logger=logging.warning
)

Tree Formatting

Format a pre-parsed lib2to3 syntax tree, useful for integration with other tools that work with Python ASTs.

def FormatTree(tree, style_config=None, lines=None):
    """
    Format a parsed lib2to3 pytree.
    
    Args:
        tree: Root node of the pytree to format
        style_config (str): Either a style name or path to style file
        lines (list): List of (start, end) tuples for line ranges to format (1-indexed)
        
    Returns:
        str: The formatted source code
    """

Usage example:

from yapf.yapflib.yapf_api import FormatTree
from yapf.pytree import pytree_utils

# Parse code to tree
code = "def hello(): print('world')"
tree = pytree_utils.ParseCodeToTree(code)

# Format the tree
formatted = FormatTree(tree, style_config='pep8')
print(formatted)

AST Formatting

Format code from a lib2to3 AST representation.

def FormatAST(ast, style_config=None, lines=None):
    """
    Format a parsed lib2to3 AST.
    
    Args:
        ast: AST to format (typically from lib2to3 parsing)
        style_config (str): Either a style name or path to style file  
        lines (list): List of (start, end) tuples for line ranges to format (1-indexed)
        
    Returns:
        str: The formatted source code
    """

Usage example:

from yapf.yapflib.yapf_api import FormatAST

# Format an AST (assumes you have an AST from lib2to3 parsing)
formatted = FormatAST(ast, style_config='pep8')
print(formatted)

File Reading

Read Python files with proper encoding detection and line ending preservation.

def ReadFile(filename, logger=None):
    """
    Read file contents with encoding detection.
    
    Args:
        filename (str): Path to file to read
        logger: Function to call for logging errors
        
    Returns:
        tuple: (source, line_ending, encoding)
            - source (str): File contents with normalized line endings
            - line_ending (str): Original line ending style ('\\n', '\\r\\n', etc.)
            - encoding (str): Detected file encoding
            
    Raises:
        IOError: If file cannot be read
        UnicodeDecodeError: If file cannot be decoded
    """

Usage example:

from yapf.yapflib.yapf_api import ReadFile

# Read file with encoding detection
source, line_ending, encoding = ReadFile('my_script.py')
print(f"File encoding: {encoding}")
print(f"Line ending: {repr(line_ending)}")

Error Handling

All formatting functions may raise YapfError exceptions for various error conditions:

from yapf.yapflib.errors import YapfError
from yapf.yapflib.yapf_api import FormatCode

try:
    formatted, changed = FormatCode("invalid python syntax +++")
except YapfError as e:
    print(f"Formatting error: {e}")

Integration Patterns

IDE Integration

from yapf.yapflib.yapf_api import FormatCode

def format_selection(code, start_line, end_line):
    """Format specific lines in an editor."""
    lines = [(start_line, end_line)]
    formatted, changed = FormatCode(code, lines=lines)
    return formatted if changed else code

def format_on_save(filename):
    """Format file on save."""
    from yapf.yapflib.yapf_api import FormatFile
    _, _, changed = FormatFile(filename, in_place=True)
    return changed

Batch Processing

import os
from yapf.yapflib.yapf_api import FormatFile

def format_project(directory, style='pep8'):
    """Format all Python files in a project."""
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.py'):
                filepath = os.path.join(root, file)
                try:
                    _, _, changed = FormatFile(
                        filepath, 
                        style_config=style,
                        in_place=True
                    )
                    if changed:
                        print(f"Formatted: {filepath}")
                except Exception as e:
                    print(f"Error formatting {filepath}: {e}")

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