or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-editorconfig

EditorConfig File Locator and Interpreter for Python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/editorconfig@0.17.x

To install, run

npx @tessl/cli install tessl/pypi-editorconfig@0.17.0

0

# EditorConfig

1

2

EditorConfig File Locator and Interpreter for Python provides the same functionality as the EditorConfig C Core, serving as both a command line program and an importable library for maintaining consistent coding styles across different text editors and projects. The package implements the EditorConfig file format specification, allowing developers to define and enforce coding style rules (indentation, line endings, character encoding, etc.) through .editorconfig files that are automatically recognized by compatible text editors and development tools.

3

4

## Package Information

5

6

- **Package Name**: EditorConfig

7

- **Package Type**: PyPI

8

- **Language**: Python

9

- **Installation**: `pip install EditorConfig`

10

- **Version**: 0.17.1

11

- **License**: PSF-2.0 (Python Software Foundation License)

12

- **Documentation**: http://pydocs.editorconfig.org

13

14

## Core Imports

15

16

Primary library usage (recommended):

17

18

```python

19

from editorconfig import get_properties, EditorConfigError

20

```

21

22

Advanced handler and exceptions (explicit imports required):

23

24

```python

25

from editorconfig.handler import EditorConfigHandler

26

from editorconfig.exceptions import ParsingError, PathError, VersionError

27

```

28

29

Alternatively available from main module:

30

31

```python

32

from editorconfig import EditorConfigHandler, ParsingError, PathError, VersionError

33

```

34

35

Utility functions (explicit imports required):

36

37

```python

38

from editorconfig.fnmatch import fnmatch, fnmatchcase, translate

39

from editorconfig.versiontools import join_version, split_version

40

```

41

42

## Basic Usage

43

44

```python

45

from editorconfig import get_properties, EditorConfigError

46

47

filename = "/home/user/project/src/main.py"

48

49

try:

50

options = get_properties(filename)

51

except EditorConfigError:

52

print("Error occurred while getting EditorConfig properties")

53

else:

54

for key, value in options.items():

55

print(f"{key}={value}")

56

# Example output:

57

# indent_style=space

58

# indent_size=4

59

# end_of_line=lf

60

# charset=utf-8

61

# trim_trailing_whitespace=true

62

# insert_final_newline=true

63

```

64

65

## Capabilities

66

67

### Configuration Resolution

68

69

Primary function to get EditorConfig properties for any file path by locating and parsing relevant .editorconfig files in the directory hierarchy.

70

71

```python { .api }

72

def get_properties(filename: str) -> OrderedDict[str, str]:

73

"""

74

Locate and parse EditorConfig files for the given filename.

75

76

Args:

77

filename (str): Absolute path to the file to get properties for

78

79

Returns:

80

OrderedDict[str, str]: Configuration properties as key-value pairs

81

82

Raises:

83

EditorConfigError: Base exception for EditorConfig-related errors

84

ParsingError: If EditorConfig file could not be parsed

85

PathError: If invalid filepath is specified

86

VersionError: If invalid version number is specified

87

"""

88

```

89

90

### Advanced Configuration Handling

91

92

Direct access to the EditorConfig handler for custom configuration filename, version compatibility, and fine-grained control over the parsing process.

93

94

```python { .api }

95

class EditorConfigHandler:

96

"""

97

Allows locating and parsing of EditorConfig files for given filename.

98

99

Provides more control over the configuration resolution process than

100

the simple get_properties() function.

101

"""

102

103

def __init__(self, filepath: str, conf_filename: str = '.editorconfig',

104

version: VersionTuple = VERSION):

105

"""

106

Create EditorConfigHandler for matching given filepath.

107

108

Args:

109

filepath (str): Absolute path to target file

110

conf_filename (str): Configuration filename (default: '.editorconfig')

111

version (VersionTuple): EditorConfig version for compatibility

112

"""

113

114

def get_configurations(self) -> OrderedDict[str, str]:

115

"""

116

Find EditorConfig files and return all options matching filepath.

117

118

Returns:

119

OrderedDict[str, str]: Configuration options as key-value pairs

120

121

Raises:

122

VersionError: If self.version is invalid EditorConfig version

123

PathError: If self.filepath is not a valid absolute filepath

124

ParsingError: If improperly formatted EditorConfig file found

125

"""

126

```

127

128

```python { .api }

129

def get_filenames(path: str, filename: str) -> list[str]:

130

"""

131

Yield full filepath for filename in each directory in and above path.

132

133

Args:

134

path (str): Directory path to start search from

135

filename (str): Name of file to search for (usually '.editorconfig')

136

137

Returns:

138

list[str]: List of full file paths in directory hierarchy

139

"""

140

```

141

142

### Pattern Matching

143

144

EditorConfig-specific file pattern matching with support for shell-style patterns, glob patterns, and brace expansion used in .editorconfig file sections.

145

146

```python { .api }

147

def fnmatch(name: str, pat: str) -> bool:

148

"""

149

Test whether FILENAME matches PATTERN using EditorConfig patterns.

150

151

Supports EditorConfig pattern matching including:

152

- * (matches everything except path separator)

153

- ** (matches everything including path separators)

154

- ? (matches any single character)

155

- [seq] (matches any character in seq)

156

- [!seq] (matches any char not in seq)

157

- {s1,s2,s3} (matches any of the strings given)

158

159

Args:

160

name (str): Filename to test

161

pat (str): EditorConfig pattern to match against

162

163

Returns:

164

bool: True if filename matches pattern

165

"""

166

```

167

168

```python { .api }

169

def fnmatchcase(name: str, pat: str) -> bool:

170

"""

171

Test whether FILENAME matches PATTERN, including case (case-sensitive).

172

173

Args:

174

name (str): Filename to test

175

pat (str): EditorConfig pattern to match against

176

177

Returns:

178

bool: True if filename matches pattern (case-sensitive)

179

"""

180

```

181

182

```python { .api }

183

def translate(pat: str, nested: bool = False) -> tuple[str, list[tuple[int, int]]]:

184

"""

185

Translate an EditorConfig shell PATTERN to a regular expression.

186

187

Args:

188

pat (str): EditorConfig pattern to translate

189

nested (bool): Whether this is a nested translation

190

191

Returns:

192

tuple[str, list[tuple[int, int]]]: Regex string and numeric groups

193

"""

194

```

195

196

### Version Management

197

198

Tools for handling and comparing EditorConfig version numbers, ensuring compatibility across different EditorConfig implementations.

199

200

```python { .api }

201

def join_version(version_tuple: VersionTuple) -> str:

202

"""

203

Return a string representation of version from given VERSION tuple.

204

205

Args:

206

version_tuple (VersionTuple): VERSION tuple to convert

207

208

Returns:

209

str: String version representation (e.g., "0.17.1")

210

"""

211

```

212

213

```python { .api }

214

def split_version(version: str) -> Optional[VersionTuple]:

215

"""

216

Return VERSION tuple for given string representation of version.

217

218

Args:

219

version (str): String version to parse

220

221

Returns:

222

Optional[VersionTuple]: VersionTuple or None if invalid

223

"""

224

```

225

226

### Command Line Interface

227

228

Complete command-line tool for direct EditorConfig file processing with support for custom configuration files and version compatibility testing.

229

230

```python { .api }

231

def main() -> None:

232

"""

233

Main entry point for command line interface.

234

235

Usage: editorconfig [OPTIONS] FILENAME

236

237

Options:

238

-f: Specify conf filename other than ".editorconfig"

239

-b: Specify version (used by devs to test compatibility)

240

-h, --help: Print help message

241

-v, --version: Display version information

242

"""

243

```

244

245

```python { .api }

246

def version() -> None:

247

"""Print version information to stdout."""

248

```

249

250

```python { .api }

251

def usage(command: str, error: bool = False) -> None:

252

"""

253

Print usage information.

254

255

Args:

256

command (str): Command name to display in usage

257

error (bool): Whether this is error usage (prints to stderr)

258

"""

259

```

260

261

### Configuration File Parsing

262

263

Specialized INI parser with EditorConfig-specific features for handling configuration file syntax, section matching, and property resolution.

264

265

```python { .api }

266

class EditorConfigParser:

267

"""

268

Parser for EditorConfig-style configuration files.

269

270

Based on RawConfigParser with EditorConfig-specific modifications:

271

- Special characters can be used in section names

272

- Octothorpe can be used for comments (not just at beginning of line)

273

- Only tracks INI options in sections that match target filename

274

- Stops parsing when root=true is found

275

"""

276

277

def __init__(self, filename: str):

278

"""

279

Initialize parser for specific target filename.

280

281

Args:

282

filename (str): Target filename for section matching

283

"""

284

285

def matches_filename(self, config_filename: str, glob: str) -> bool:

286

"""

287

Return True if section glob matches target filename.

288

289

Args:

290

config_filename (str): Path to the config file

291

glob (str): Glob pattern from config file section

292

293

Returns:

294

bool: True if pattern matches target filename

295

"""

296

297

def read(self, filename: str) -> None:

298

"""

299

Read and parse single EditorConfig file.

300

301

Args:

302

filename (str): Path to EditorConfig file to parse

303

"""

304

305

def optionxform(self, optionstr: str) -> str:

306

"""

307

Transform option names to lowercase.

308

309

Args:

310

optionstr (str): Option name to transform

311

312

Returns:

313

str: Lowercase option name

314

"""

315

```

316

317

## Exception Handling

318

319

EditorConfig provides a comprehensive exception hierarchy for different error conditions that may occur during configuration file processing.

320

321

```python { .api }

322

class EditorConfigError(Exception):

323

"""Parent class of all exceptions raised by EditorConfig."""

324

```

325

326

```python { .api }

327

from configparser import ParsingError as _ParsingError

328

329

class ParsingError(_ParsingError, EditorConfigError):

330

"""Error raised if an EditorConfig file could not be parsed."""

331

```

332

333

```python { .api }

334

class PathError(ValueError, EditorConfigError):

335

"""Error raised if invalid filepath is specified."""

336

```

337

338

```python { .api }

339

class VersionError(ValueError, EditorConfigError):

340

"""Error raised if invalid version number is specified."""

341

```

342

343

## Types

344

345

```python { .api }

346

from collections import OrderedDict

347

from typing import Optional

348

349

VersionTuple = tuple[int, int, int, str]

350

```

351

352

### Constants

353

354

```python { .api }

355

VERSION = (0, 17, 1, "final") # Current package version tuple

356

__version__ = "0.17.1" # Package version string

357

```

358

359

## Usage Examples

360

361

### Basic Configuration Retrieval

362

363

```python

364

from editorconfig import get_properties

365

366

# Get properties for a Python file

367

filename = "/home/user/project/src/main.py"

368

properties = get_properties(filename)

369

370

# Properties might include:

371

# {'indent_style': 'space', 'indent_size': '4', 'end_of_line': 'lf'}

372

```

373

374

### Advanced Handler Usage

375

376

```python

377

from editorconfig.handler import EditorConfigHandler

378

379

# Create handler with custom config filename

380

handler = EditorConfigHandler(

381

filepath="/home/user/project/src/main.py",

382

conf_filename=".my-editorconfig"

383

)

384

385

# Get configurations

386

options = handler.get_configurations()

387

for key, value in options.items():

388

print(f"{key}={value}")

389

```

390

391

### Pattern Matching

392

393

```python

394

from editorconfig.fnmatch import fnmatch

395

396

# Test if filename matches EditorConfig pattern

397

matches = fnmatch("src/main.py", "*.py") # True

398

matches = fnmatch("src/test.js", "*.py") # False

399

matches = fnmatch("src/components/Button.tsx", "**/*.{ts,tsx}") # True

400

```

401

402

### Error Handling

403

404

```python

405

from editorconfig import get_properties

406

from editorconfig.exceptions import ParsingError, PathError, VersionError

407

408

try:

409

properties = get_properties("/path/to/file.py")

410

except ParsingError as e:

411

print(f"Configuration file parsing error: {e}")

412

except PathError as e:

413

print(f"Invalid file path: {e}")

414

except VersionError as e:

415

print(f"Version compatibility error: {e}")

416

```

417

418

### Command Line Usage

419

420

```bash

421

# Get properties for a file

422

editorconfig /path/to/file.py

423

424

# Use custom config filename

425

editorconfig -f .my-editorconfig /path/to/file.py

426

427

# Test compatibility with specific version

428

editorconfig -b 0.15.0 /path/to/file.py

429

430

# Show help

431

editorconfig --help

432

433

# Show version

434

editorconfig --version

435

```