or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-yapf

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/yapf@0.43.x

To install, run

npx @tessl/cli install tessl/pypi-yapf@0.43.0

0

# YAPF

1

2

YAPF (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.

3

4

## Package Information

5

6

- **Package Name**: yapf

7

- **Language**: Python

8

- **Installation**: `pip install yapf`

9

- **Version**: 0.43.0

10

11

## Core Imports

12

13

```python

14

# Core formatting API

15

from yapf.yapflib.yapf_api import FormatCode, FormatFile, FormatTree, FormatAST, ReadFile

16

17

# Style configuration

18

from yapf.yapflib import style

19

from yapf.yapflib.style import StyleConfigError

20

21

# File operations

22

from yapf.yapflib import file_resources

23

24

# Error handling

25

from yapf.yapflib.errors import YapfError, FormatErrorMsg

26

27

# Command line interface

28

import yapf

29

```

30

31

## Basic Usage

32

33

```python

34

from yapf.yapflib.yapf_api import FormatCode

35

36

# Format a string of Python code

37

unformatted_code = '''

38

def hello(name):

39

print("Hello, "+name+"!")

40

'''

41

42

formatted_code, changed = FormatCode(unformatted_code)

43

print(formatted_code)

44

# Output:

45

# def hello(name):

46

# print("Hello, " + name + "!")

47

48

# Format with specific style

49

formatted_code, changed = FormatCode(

50

unformatted_code,

51

style_config='google'

52

)

53

54

# Format a file

55

from yapf.yapflib.yapf_api import FormatFile

56

result, encoding, changed = FormatFile('my_script.py')

57

```

58

59

Command line usage:

60

```bash

61

# Format a file in place

62

yapf -i my_script.py

63

64

# Format and show diff

65

yapf -d my_script.py

66

67

# Format with specific style

68

yapf --style=google my_script.py

69

70

# Format recursively

71

yapf -r -i my_project/

72

```

73

74

## Architecture

75

76

YAPF's architecture is built around several key components:

77

78

- **Parser**: Converts Python code into a parse tree using lib2to3

79

- **Unwrapper**: Transforms the parse tree into logical lines that represent formatting decisions

80

- **Style Engine**: Applies configurable formatting rules based on style configurations

81

- **Reformatter**: Uses a priority queue algorithm to determine optimal line breaks and formatting

82

- **File Resources**: Handles file I/O, encoding detection, and configuration management

83

84

This design allows YAPF to make sophisticated formatting decisions while maintaining configurability through style settings.

85

86

## Capabilities

87

88

### Core Formatting API

89

90

Primary functions for formatting Python code, including string formatting, file formatting, and tree-based formatting with configurable styles and line-specific formatting options.

91

92

```python { .api }

93

def FormatCode(unformatted_source, filename='<unknown>', style_config=None, lines=None, print_diff=False):

94

"""

95

Format a string of Python code.

96

97

Args:

98

unformatted_source (str): The code to format

99

filename (str): Name of file being reformatted

100

style_config (str): Style name or file path

101

lines (list): List of (start, end) line ranges to format

102

print_diff (bool): Return diff instead of formatted code

103

104

Returns:

105

tuple: (reformatted_source, changed)

106

"""

107

108

def FormatFile(filename, style_config=None, lines=None, print_diff=False, in_place=False, logger=None):

109

"""

110

Format a single Python file.

111

112

Args:

113

filename (str): File to reformat

114

style_config (str): Style name or file path

115

lines (list): List of (start, end) line ranges to format

116

print_diff (bool): Return diff instead of formatted code

117

in_place (bool): Write reformatted code back to file

118

logger: Stream for logging output

119

120

Returns:

121

tuple: (reformatted_code, encoding, changed)

122

"""

123

124

def FormatTree(tree, style_config=None, lines=None):

125

"""

126

Format a parsed lib2to3 pytree.

127

128

Args:

129

tree: Root of pytree to format

130

style_config (str): Style name or file path

131

lines (list): List of (start, end) line ranges to format

132

133

Returns:

134

str: Formatted source code

135

"""

136

```

137

138

[Core Formatting API](./core-formatting.md)

139

140

### Style Configuration

141

142

Comprehensive style configuration system supporting predefined styles (PEP8, Google, Facebook) and custom configurations through files or programmatic settings.

143

144

```python { .api }

145

def Get(setting_name):

146

"""Get a style setting value."""

147

148

def SetGlobalStyle(style):

149

"""Set global style configuration."""

150

151

def CreateStyleFromConfig(style_config):

152

"""Create style from config string or file."""

153

154

def Help():

155

"""Return dict mapping style names to help strings."""

156

```

157

158

[Style Configuration](./style-configuration.md)

159

160

### File Operations

161

162

File handling utilities for reading Python files with proper encoding detection, writing formatted code, and managing configuration files and exclude patterns.

163

164

```python { .api }

165

def ReadFile(filename, logger=None):

166

"""

167

Read file contents with encoding detection.

168

169

Args:

170

filename (str): Name of file to read

171

logger: Function for logging messages

172

173

Returns:

174

tuple: (source, line_ending, encoding)

175

"""

176

```

177

178

[File Operations](./file-operations.md)

179

180

### Command Line Interface

181

182

Complete command-line interface supporting file formatting, directory recursion, parallel processing, and various output modes including in-place editing and diff generation.

183

184

```python { .api }

185

def main(argv):

186

"""

187

Main command-line entry point.

188

189

Args:

190

argv (list): Command-line arguments including program name

191

192

Returns:

193

int: Exit code (0 for success)

194

"""

195

196

def FormatFiles(filenames, lines, style_config=None, no_local_style=False,

197

in_place=False, print_diff=False, parallel=False,

198

quiet=False, verbose=False, print_modified=False):

199

"""

200

Format multiple files with various options.

201

202

Args:

203

filenames (list): List of files to reformat

204

lines (list): List of (start, end) line ranges

205

style_config (str): Style name or file path

206

no_local_style (bool): Don't search for local style config

207

in_place (bool): Modify files in place

208

print_diff (bool): Show diff instead of formatted code

209

parallel (bool): Use parallel processing

210

quiet (bool): Suppress output

211

verbose (bool): Show filenames while processing

212

print_modified (bool): Show names of modified files

213

214

Returns:

215

bool: True if any source code changed

216

"""

217

```

218

219

[Command Line Interface](./command-line.md)

220

221

## Types

222

223

```python { .api }

224

class YapfError(Exception):

225

"""Base exception class for YAPF errors."""

226

227

class StyleConfigError(YapfError):

228

"""Raised when there's a problem reading the style configuration."""

229

```

230

231

## Constants

232

233

```python { .api }

234

# Regex patterns for controlling YAPF formatting

235

DISABLE_PATTERN = r'^#.*\b(?:yapf:\s*disable|fmt: ?off)\b'

236

ENABLE_PATTERN = r'^#.*\b(?:yapf:\s*enable|fmt: ?on)\b'

237

```

238

239

## Utility Functions

240

241

```python { .api }

242

def FormatErrorMsg(e):

243

"""

244

Convert an exception into a standard format.

245

246

The standard error message format is:

247

<filename>:<lineno>:<column>: <msg>

248

249

Args:

250

e: An exception

251

252

Returns:

253

str: A properly formatted error message string

254

"""

255

```