or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ansi-styling.mddebug.mdindex.mdpretty-printing.mdpytest-plugin.mdtiming.md

pretty-printing.mddocs/

0

# Pretty Printing

1

2

Advanced pretty printing system for complex Python data structures with intelligent formatting, syntax highlighting, configurable output parameters, and special handling for various object types including dataclasses, numpy arrays, SQLAlchemy models, and custom objects with `__pretty__` methods.

3

4

## Capabilities

5

6

### Pretty Format Function

7

8

The main pretty formatting function that converts Python objects to nicely formatted strings.

9

10

```python { .api }

11

def pformat(value, indent=0, indent_first=False, highlight=False) -> str:

12

"""

13

Format value as pretty string with intelligent structure formatting.

14

15

Parameters:

16

- value: Object to format

17

- indent: Initial indentation level (default: 0)

18

- indent_first: Indent the first line (default: False)

19

- highlight: Apply syntax highlighting with Pygments (default: False)

20

21

Returns:

22

Formatted string representation with proper indentation and structure

23

"""

24

```

25

26

Usage examples:

27

28

```python

29

from devtools import pformat

30

31

# Format complex nested data

32

data = {

33

'users': [

34

{'name': 'Alice', 'age': 30, 'active': True},

35

{'name': 'Bob', 'age': 25, 'active': False}

36

],

37

'config': {

38

'debug': True,

39

'timeout': 30.0,

40

'retries': 3

41

}

42

}

43

44

formatted = pformat(data, highlight=True)

45

print(formatted)

46

# Output: Nicely indented structure with syntax highlighting

47

48

# Format with custom indentation

49

formatted_indented = pformat(data, indent=4, indent_first=True)

50

print(formatted_indented)

51

```

52

53

### Pretty Print Function

54

55

Convenience function that pretty prints directly to stdout or a file with automatic highlighting detection.

56

57

```python { .api }

58

def pprint(s, file=None) -> None:

59

"""

60

Pretty print with automatic highlighting detection based on TTY status.

61

62

Parameters:

63

- s: Object to pretty print

64

- file: Output file (default: stdout)

65

"""

66

```

67

68

Usage examples:

69

70

```python

71

from devtools import pprint

72

import numpy as np

73

74

# Pretty print to stdout with auto-highlighting

75

complex_data = {

76

'matrix': np.array([[1, 2, 3], [4, 5, 6]]),

77

'text': 'A very long string that will be wrapped appropriately for better readability',

78

'nested': {'a': [1, 2, 3], 'b': {4, 5, 6}}

79

}

80

pprint(complex_data)

81

82

# Pretty print to file

83

with open('output.txt', 'w') as f:

84

pprint(complex_data, file=f)

85

```

86

87

### PrettyFormat Class

88

89

Configurable pretty formatting class that allows customization of all formatting parameters.

90

91

```python { .api }

92

class PrettyFormat:

93

"""

94

Configurable pretty formatter for complex data structures.

95

"""

96

def __init__(

97

self,

98

indent_step: int = 4,

99

indent_char: str = ' ',

100

repr_strings: bool = False,

101

simple_cutoff: int = 10,

102

width: int = 120,

103

yield_from_generators: bool = True

104

):

105

"""

106

Initialize PrettyFormat with custom formatting options.

107

108

Parameters:

109

- indent_step: Number of spaces per indentation level (default: 4)

110

- indent_char: Character used for indentation (default: ' ')

111

- repr_strings: Use repr() for strings instead of pretty formatting (default: False)

112

- simple_cutoff: Maximum length for simple one-line representation (default: 10)

113

- width: Maximum line width for formatting (default: 120)

114

- yield_from_generators: Iterate through generators for display (default: True)

115

"""

116

117

def __call__(self, value, indent=0, indent_first=False, highlight=False) -> str:

118

"""

119

Format value as pretty string.

120

121

Parameters:

122

- value: Object to format

123

- indent: Initial indentation level

124

- indent_first: Indent the first line

125

- highlight: Apply syntax highlighting

126

127

Returns:

128

Formatted string representation

129

"""

130

```

131

132

Usage examples:

133

134

```python

135

from devtools import PrettyFormat

136

137

# Create custom formatter with different settings

138

compact_formatter = PrettyFormat(

139

indent_step=2,

140

width=80,

141

simple_cutoff=20

142

)

143

144

# Create formatter that always uses repr for strings

145

repr_formatter = PrettyFormat(repr_strings=True)

146

147

# Use custom formatter

148

data = {'key': 'value', 'numbers': [1, 2, 3, 4, 5]}

149

compact_output = compact_formatter(data)

150

repr_output = repr_formatter(data)

151

```

152

153

### Special Object Support

154

155

The pretty printer includes built-in support for various special object types:

156

157

#### Dataclasses

158

159

```python

160

from dataclasses import dataclass

161

from devtools import pprint

162

163

@dataclass

164

class Person:

165

name: str

166

age: int

167

active: bool = True

168

169

person = Person("Alice", 30)

170

pprint(person)

171

# Output: Person(

172

# name='Alice',

173

# age=30,

174

# active=True,

175

# )

176

```

177

178

#### Named Tuples

179

180

```python

181

from collections import namedtuple

182

from devtools import pprint

183

184

Point = namedtuple('Point', ['x', 'y', 'z'])

185

point = Point(1.0, 2.0, 3.0)

186

pprint(point)

187

# Output: Point(

188

# x=1.0,

189

# y=2.0,

190

# z=3.0,

191

# )

192

```

193

194

#### Generators and Iterators

195

196

```python

197

from devtools import pprint

198

199

def number_generator():

200

for i in range(5):

201

yield i * 2

202

203

# Generator contents are displayed when yield_from_generators=True

204

pprint(number_generator())

205

# Output: (

206

# 0,

207

# 2,

208

# 4,

209

# 6,

210

# 8,

211

# )

212

```

213

214

#### Long Strings and Multiline Text

215

216

```python

217

from devtools import pprint

218

219

long_text = "This is a very long string that will be wrapped across multiple lines to improve readability and fit within the specified width constraints."

220

221

pprint(long_text)

222

# Output: (

223

# 'This is a very long string that will be wrapped across '

224

# 'multiple lines to improve readability and fit within the '

225

# 'specified width constraints.'

226

# )

227

```

228

229

### Custom Pretty Methods

230

231

Objects can implement custom pretty formatting by defining a `__pretty__` method:

232

233

```python

234

class CustomObject:

235

def __init__(self, data):

236

self.data = data

237

238

def __pretty__(self, fmt, skip_exc):

239

yield 'CustomObject('

240

yield 1 # Increase indentation

241

yield fmt({'data': self.data})

242

yield -1 # Decrease indentation

243

yield ')'

244

245

from devtools import pprint

246

obj = CustomObject([1, 2, 3])

247

pprint(obj)

248

# Output: CustomObject(

249

# {'data': [1, 2, 3]}

250

# )

251

```

252

253

### Format Helper Function

254

255

Utility function for custom pretty formatting implementations.

256

257

```python { .api }

258

def fmt(v) -> dict:

259

"""

260

Helper function for custom pretty formatting.

261

262

Parameters:

263

- v: Value to format

264

265

Returns:

266

Dictionary with special pretty formatting key

267

"""

268

```

269

270

### Skip Pretty Exception

271

272

Exception class for skipping pretty formatting in custom `__pretty__` methods.

273

274

```python { .api }

275

class SkipPretty(Exception):

276

"""

277

Exception raised to skip pretty formatting and fall back to repr().

278

"""

279

```

280

281

Usage in custom `__pretty__` methods:

282

283

```python

284

class ConditionalPretty:

285

def __init__(self, data, should_pretty=True):

286

self.data = data

287

self.should_pretty = should_pretty

288

289

def __pretty__(self, fmt, skip_exc):

290

if not self.should_pretty:

291

raise skip_exc # Falls back to repr()

292

yield f'ConditionalPretty({self.data})'

293

```

294

295

### SQLAlchemy Integration

296

297

Special support for SQLAlchemy ORM models with deferred attribute handling:

298

299

```python

300

# Assuming SQLAlchemy model

301

from devtools import pprint

302

303

# SQLAlchemy model instance

304

user = User(name="Alice", email="alice@example.com")

305

pprint(user)

306

# Output: User(

307

# id=1,

308

# name='Alice',

309

# email='alice@example.com',

310

# posts=<deferred>, # Deferred attributes shown as <deferred>

311

# )

312

```

313

314

### Environment Variables

315

316

Pretty printing behavior can be customized via environment variables:

317

318

- `PY_DEVTOOLS_INDENT`: Default indentation step (default: 4)

319

- `PY_DEVTOOLS_SIMPLE_CUTOFF`: Simple representation cutoff (default: 10)

320

- `PY_DEVTOOLS_WIDTH`: Output width (default: 120)

321

- `PY_DEVTOOLS_YIELD_FROM_GEN`: Yield from generators (default: True)

322

- `PY_DEVTOOLS_HIGHLIGHT`: Force highlighting on/off

323

324

## Types

325

326

```python { .api }

327

# Default pretty formatter instance

328

pformat: PrettyFormat

329

330

# Internal constants

331

MISSING: object # Sentinel object for missing values

332

PRETTY_KEY: str # Key for pretty formatting dict

333

```