or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

formatting.mdframe-analysis.mdindex.mdserialization.md

formatting.mddocs/

0

# Text Formatting

1

2

Comprehensive text formatting system for displaying stack traces and frame information with syntax highlighting, variable display, customizable output options, and support for both plain text and HTML output formats.

3

4

## Capabilities

5

6

### Formatter Configuration

7

8

Central formatting class that provides customizable text output for stack traces, exceptions, and frame information with extensive styling and display options.

9

10

```python { .api }

11

class Formatter:

12

def __init__(self, *,

13

options: Optional[Options] = None,

14

pygmented: bool = False,

15

show_executing_node: bool = True,

16

pygments_formatter_cls = None,

17

pygments_formatter_kwargs: Optional[dict] = None,

18

pygments_style: str = "monokai",

19

executing_node_modifier: str = "bg:#005080",

20

executing_node_underline: str = "^",

21

current_line_indicator: str = "-->",

22

line_gap_string: str = "(...)",

23

line_number_gap_string: str = ":",

24

line_number_format_string: str = "{:4} | ",

25

show_variables: bool = False,

26

use_code_qualname: bool = True,

27

show_linenos: bool = True,

28

strip_leading_indent: bool = True,

29

html: bool = False,

30

chain: bool = True,

31

collapse_repeated_frames: bool = True):

32

"""

33

Create Formatter with extensive customization options.

34

35

Args:

36

options: Stack data options for frame analysis

37

pygmented: Whether to use syntax highlighting

38

show_executing_node: Whether to highlight executing node

39

pygments_formatter_cls: Custom Pygments formatter class

40

pygments_formatter_kwargs: Arguments for Pygments formatter

41

pygments_style: Pygments style name for syntax highlighting

42

executing_node_modifier: CSS-like modifier for executing node highlighting

43

executing_node_underline: Character for underlining executing node

44

current_line_indicator: Indicator string for current line

45

line_gap_string: String to show for line gaps

46

line_number_gap_string: String for line number gaps

47

line_number_format_string: Format string for line numbers

48

show_variables: Whether to show variable values

49

use_code_qualname: Whether to use qualified names for code objects

50

show_linenos: Whether to show line numbers

51

strip_leading_indent: Whether to strip leading indentation

52

html: Whether to generate HTML output

53

chain: Whether to chain exception causes and contexts

54

collapse_repeated_frames: Whether to collapse repeated frames

55

"""

56

```

57

58

### Exception Formatting

59

60

High-level functions for formatting and displaying exceptions with enhanced context, variable information, and customizable styling.

61

62

```python { .api }

63

def print_exception(self, e: Optional[BaseException] = None, *,

64

file = None) -> None:

65

"""

66

Print formatted exception with enhanced display.

67

68

Args:

69

e: Exception to format (uses sys.exc_info() if None)

70

file: File object to write to (uses sys.stderr if None)

71

"""

72

73

def format_exception(self, e: Optional[BaseException] = None) -> Iterable[str]:

74

"""

75

Format exception as iterable of strings.

76

77

Args:

78

e: Exception to format (uses sys.exc_info() if None)

79

80

Yields:

81

Formatted strings for each part of the exception display

82

"""

83

84

def set_hook(self) -> None:

85

"""Install this formatter as sys.excepthook for automatic exception formatting."""

86

```

87

88

### Stack Formatting

89

90

Functions for formatting and displaying stack traces with detailed frame information, source context, and variable inspection.

91

92

```python { .api }

93

def print_stack(self, frame_or_tb: Optional[Union[FrameType, TracebackType]] = None,

94

*, file = None) -> None:

95

"""

96

Print formatted stack trace.

97

98

Args:

99

frame_or_tb: Frame or traceback to start from (uses current frame if None)

100

file: File object to write to (uses sys.stderr if None)

101

"""

102

103

def format_stack(self, frame_or_tb: Optional[Union[FrameType, TracebackType]] = None) -> Iterable[str]:

104

"""

105

Format stack trace as iterable of strings.

106

107

Args:

108

frame_or_tb: Frame or traceback to start from (uses current frame if None)

109

110

Yields:

111

Formatted strings for each part of the stack display

112

"""

113

114

def format_stack_data(self, stack: Iterable[Union[FrameInfo, RepeatedFrames]]) -> Iterable[str]:

115

"""

116

Format stack data objects as strings.

117

118

Args:

119

stack: Iterable of FrameInfo and RepeatedFrames objects

120

121

Yields:

122

Formatted strings for each stack element

123

"""

124

```

125

126

### Frame Formatting

127

128

Detailed formatting functions for individual stack frames, including headers, source lines, and variable display.

129

130

```python { .api }

131

def format_frame(self, frame: Union[FrameInfo, FrameType, TracebackType]) -> Iterable[str]:

132

"""

133

Format individual frame with source code and context.

134

135

Args:

136

frame: Frame object to format (FrameInfo, FrameType, or TracebackType)

137

138

Yields:

139

Formatted strings for frame display

140

"""

141

142

def format_frame_header(self, frame_info: FrameInfo) -> str:

143

"""

144

Format frame header with file and function information.

145

146

Args:

147

frame_info: FrameInfo object

148

149

Returns:

150

Formatted header string

151

"""

152

153

def format_repeated_frames(self, repeated_frames: RepeatedFrames) -> str:

154

"""

155

Format repeated frames with count and description.

156

157

Args:

158

repeated_frames: RepeatedFrames object

159

160

Returns:

161

Formatted string describing repeated frames

162

"""

163

```

164

165

### Line Formatting

166

167

Functions for formatting individual source code lines with line numbers, indicators, and syntax highlighting.

168

169

```python { .api }

170

def format_line(self, line: Line) -> str:

171

"""

172

Format individual source code line.

173

174

Args:

175

line: Line object to format

176

177

Returns:

178

Formatted line string with line number and indicators

179

"""

180

181

def format_blank_lines_linenumbers(self, blank_line: BlankLineRange) -> str:

182

"""

183

Format line numbers for blank line ranges.

184

185

Args:

186

blank_line: BlankLineRange object

187

188

Returns:

189

Formatted line number string for blank lines

190

"""

191

192

def print_lines(self, lines: Iterable[str], *, file = None) -> None:

193

"""

194

Print formatted lines to file.

195

196

Args:

197

lines: Iterable of formatted strings

198

file: File object to write to (uses sys.stdout if None)

199

"""

200

```

201

202

### Variable Formatting

203

204

Functions for formatting variable information including names, values, and type information.

205

206

```python { .api }

207

def format_variables(self, frame_info: FrameInfo) -> Iterable[str]:

208

"""

209

Format all variables in frame.

210

211

Args:

212

frame_info: FrameInfo object containing variables

213

214

Yields:

215

Formatted strings for each variable

216

"""

217

218

def format_variable(self, var: Variable) -> str:

219

"""

220

Format individual variable with name and value.

221

222

Args:

223

var: Variable object to format

224

225

Returns:

226

Formatted string showing variable name and value

227

"""

228

229

def format_variable_value(self, value: Any) -> str:

230

"""

231

Format variable value with appropriate representation.

232

233

Args:

234

value: Variable value to format

235

236

Returns:

237

Formatted string representation of the value

238

"""

239

```

240

241

## Usage Examples

242

243

### Basic Exception Formatting

244

245

```python

246

from stack_data import Formatter

247

248

# Create formatter with default settings

249

formatter = Formatter()

250

251

# Install as exception hook

252

formatter.set_hook()

253

254

# Now all exceptions will use enhanced formatting

255

try:

256

result = 1 / 0

257

except Exception as e:

258

# This will use the enhanced formatter

259

raise

260

261

# Or format manually

262

try:

263

result = 1 / 0

264

except Exception as e:

265

formatter.print_exception(e)

266

```

267

268

### Customized Stack Display

269

270

```python

271

from stack_data import Formatter, Options, BlankLines

272

273

# Create formatter with custom options

274

formatter = Formatter(

275

pygmented=True, # Enable syntax highlighting

276

show_variables=True, # Show variable values

277

show_executing_node=True, # Highlight current node

278

current_line_indicator=">>>", # Custom line indicator

279

pygments_style="github-dark", # Dark theme

280

show_linenos=True, # Show line numbers

281

options=Options(

282

before=5, # More context before

283

after=3, # More context after

284

blank_lines=BlankLines.SINGLE # Collapse blank lines

285

)

286

)

287

288

# Print current stack

289

formatter.print_stack()

290

```

291

292

### HTML Output

293

294

```python

295

from stack_data import Formatter

296

297

# Create HTML formatter

298

html_formatter = Formatter(

299

html=True, # Generate HTML output

300

pygmented=True, # Syntax highlighting in HTML

301

show_variables=True, # Include variables

302

pygments_style="monokai" # Dark style for HTML

303

)

304

305

# Get HTML output as strings

306

try:

307

result = 1 / 0

308

except Exception as e:

309

html_lines = list(html_formatter.format_exception(e))

310

html_output = ''.join(html_lines)

311

print(html_output)

312

```

313

314

### Variable Display Control

315

316

```python

317

from stack_data import Formatter

318

319

# Formatter focused on variable display

320

var_formatter = Formatter(

321

show_variables=True,

322

show_executing_node=False, # Focus on variables, not execution

323

show_linenos=False, # Cleaner display

324

strip_leading_indent=True, # Remove indentation

325

current_line_indicator="*" # Subtle indicator

326

)

327

328

import inspect

329

frame = inspect.currentframe()

330

331

# Format just the current frame

332

for line in var_formatter.format_frame(frame):

333

print(line, end='')

334

```

335

336

### Custom Styling

337

338

```python

339

from stack_data import Formatter

340

341

# Formatter with custom styling

342

styled_formatter = Formatter(

343

pygmented=True,

344

executing_node_modifier="bg:#ff0000", # Red background for current node

345

executing_node_underline="^", # Underline character

346

line_gap_string="[... skipped lines ...]", # Custom gap indicator

347

line_number_format_string="{:6d} | ", # Wider line numbers

348

pygments_style="material" # Material design colors

349

)

350

351

styled_formatter.print_stack()

352

```

353

354

### Exception Chaining

355

356

```python

357

from stack_data import Formatter

358

359

# Formatter with exception chaining

360

chain_formatter = Formatter(

361

chain=True, # Show exception causes and contexts

362

show_variables=True, # Show variables in all frames

363

collapse_repeated_frames=True # Collapse recursive calls

364

)

365

366

def outer():

367

try:

368

inner()

369

except ValueError as e:

370

raise RuntimeError("Outer error") from e

371

372

def inner():

373

raise ValueError("Inner error")

374

375

try:

376

outer()

377

except Exception as e:

378

chain_formatter.print_exception(e)

379

# Will show both ValueError and RuntimeError with full context

380

```

381

382

### Minimal Output

383

384

```python

385

from stack_data import Formatter

386

387

# Minimal formatter for clean output

388

minimal_formatter = Formatter(

389

pygmented=False, # No syntax highlighting

390

show_variables=False, # No variables

391

show_executing_node=False, # No highlighting

392

show_linenos=False, # No line numbers

393

current_line_indicator="", # No indicator

394

strip_leading_indent=True, # Clean indentation

395

collapse_repeated_frames=True # Collapse recursion

396

)

397

398

minimal_formatter.print_stack()

399

```