or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdconfig-logging.mdexceptions.mdformatting.mdindex.mdprogrammatic-api.md

programmatic-api.mddocs/

0

# Programmatic API

1

2

The stable public API for integrating flake8 into other tools and applications. This API provides programmatic access to flake8's code checking functionality with full configuration control.

3

4

## Capabilities

5

6

### Style Guide Creation

7

8

Create a configured StyleGuide instance for checking Python files programmatically.

9

10

```python { .api }

11

def get_style_guide(**kwargs) -> StyleGuide:

12

"""

13

Provision a StyleGuide for programmatic use.

14

15

This is the main entry point for programmatic flake8 usage. Creates and

16

configures a StyleGuide instance that can be used to check files.

17

18

Parameters:

19

**kwargs: Configuration options that correspond to command-line options:

20

- exclude: List of patterns to exclude files/directories

21

- select: List of error codes to check for

22

- ignore: List of error codes to ignore

23

- max_line_length: Maximum line length (default 79)

24

- max_complexity: Maximum cyclomatic complexity

25

- show_source: Show source lines in output

26

- statistics: Show violation statistics

27

- count: Show count of violations

28

- format: Output format string

29

- output_file: File to write results to

30

31

Returns:

32

StyleGuide: Configured instance ready for checking files

33

34

Example:

35

style_guide = get_style_guide(

36

exclude=['migrations', '*.pyc'],

37

ignore=['E203', 'W503'],

38

max_line_length=88

39

)

40

"""

41

```

42

43

Usage example:

44

45

```python

46

from flake8.api import legacy

47

48

# Create style guide with custom configuration

49

style_guide = legacy.get_style_guide(

50

exclude=['migrations', 'venv', '.git'],

51

ignore=['E203', 'W503'], # Ignore specific error codes

52

max_line_length=88,

53

show_source=True

54

)

55

56

# Check files

57

report = style_guide.check_files(['myproject/'])

58

print(f"Found {report.total_errors} violations")

59

```

60

61

### File Checking

62

63

Check Python files for code quality violations using a configured StyleGuide.

64

65

```python { .api }

66

class StyleGuide:

67

"""

68

Main interface for programmatic file checking.

69

70

This class provides methods to check files, determine exclusions,

71

and configure reporting options.

72

"""

73

74

def check_files(self, paths: list[str] | None = None) -> Report:

75

"""

76

Run flake8 checks on specified files and return results.

77

78

Parameters:

79

paths: List of file paths or directories to check.

80

If None, uses paths from command line options.

81

82

Returns:

83

Report: Object containing check results and statistics

84

85

Example:

86

report = style_guide.check_files(['app.py', 'tests/'])

87

"""

88

89

def excluded(self, filename: str, parent: str | None = None) -> bool:

90

"""

91

Determine if a file should be excluded from checking.

92

93

Parameters:

94

filename: Path to the file to check

95

parent: Parent directory path (optional)

96

97

Returns:

98

bool: True if file should be excluded, False otherwise

99

100

Example:

101

if not style_guide.excluded('myfile.py'):

102

# File will be checked

103

"""

104

105

def input_file(self, filename: str, lines=None, expected=None, line_offset=0) -> Report:

106

"""

107

Check a single file and return results.

108

109

Parameters:

110

filename: Path to file to check

111

lines: Ignored (legacy parameter)

112

expected: Ignored (legacy parameter)

113

line_offset: Ignored (legacy parameter)

114

115

Returns:

116

Report: Check results for the single file

117

"""

118

119

def init_report(self, reporter=None) -> None:

120

"""

121

Initialize a custom formatter for output.

122

123

Parameters:

124

reporter: Custom BaseFormatter subclass for output formatting

125

If None, uses default formatter

126

"""

127

128

@property

129

def options(self):

130

"""Access to parsed configuration options."""

131

132

@property

133

def paths(self) -> list[str]:

134

"""List of file paths configured for checking."""

135

```

136

137

Usage example:

138

139

```python

140

# Check specific files

141

report = style_guide.check_files(['app.py', 'utils.py'])

142

143

# Check if file would be excluded

144

if style_guide.excluded('migrations/0001_initial.py'):

145

print("File is excluded from checking")

146

147

# Check single file

148

single_report = style_guide.input_file('test.py')

149

```

150

151

### Results and Reporting

152

153

Access check results and violation statistics through the Report interface.

154

155

```python { .api }

156

class Report:

157

"""

158

Results and statistics from a flake8 check run.

159

160

Provides access to error counts, violation statistics, and detailed

161

results from checking operations.

162

"""

163

164

@property

165

def total_errors(self) -> int:

166

"""

167

Total number of errors and warnings found.

168

169

Returns:

170

int: Count of all violations found during checking

171

"""

172

173

def get_statistics(self, violation: str) -> list[str]:

174

"""

175

Get occurrence statistics for a specific violation code.

176

177

Returns formatted statistics showing count, error code, and message

178

for each occurrence of the specified violation type.

179

180

Parameters:

181

violation: Error code to get statistics for (e.g., 'E501', 'W503')

182

183

Returns:

184

list[str]: List of formatted statistics strings in format:

185

"{count} {error_code} {message}"

186

187

Example:

188

stats = report.get_statistics('E501')

189

# Returns: ['3 E501 line too long (82 > 79 characters)']

190

"""

191

```

192

193

Usage example:

194

195

```python

196

# Get total error count

197

total = report.total_errors

198

print(f"Total violations: {total}")

199

200

# Get statistics for specific error codes

201

line_length_stats = report.get_statistics('E501')

202

for stat in line_length_stats:

203

print(f"Line length violation: {stat}")

204

205

# Get all import-related violations

206

import_stats = report.get_statistics('E401')

207

for stat in import_stats:

208

print(f"Import issue: {stat}")

209

```

210

211

## Complete Example

212

213

```python

214

from flake8.api import legacy

215

216

def check_code_quality(project_path, config=None):

217

"""Check code quality for a Python project."""

218

219

# Configure style guide

220

config = config or {}

221

style_guide = legacy.get_style_guide(

222

exclude=config.get('exclude', ['migrations', '.git', '__pycache__']),

223

ignore=config.get('ignore', []),

224

max_line_length=config.get('max_line_length', 88),

225

show_source=True,

226

statistics=True

227

)

228

229

# Run checks

230

report = style_guide.check_files([project_path])

231

232

# Report results

233

print(f"Code quality check complete!")

234

print(f"Total violations found: {report.total_errors}")

235

236

# Show statistics for common violations

237

common_errors = ['E501', 'E302', 'E305', 'W291', 'F401']

238

for error_code in common_errors:

239

stats = report.get_statistics(error_code)

240

if stats:

241

print(f"\n{error_code} violations:")

242

for stat in stats:

243

print(f" {stat}")

244

245

return report.total_errors == 0

246

247

# Usage

248

if __name__ == "__main__":

249

is_clean = check_code_quality("myproject/")

250

exit(0 if is_clean else 1)

251

```