or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-interface.mdcolor-system.mdconfiguration.mdcore-formatting.mddefault-hooks.mdglobal-hooks.mdindex.mdprinting.mdutilities.md

configuration.mddocs/

0

# Configuration and Formatting

1

2

Comprehensive formatting configuration system with customizable output options, color schemes, variable filtering, and display preferences. The Format class provides fine-grained control over every aspect of traceback display and variable representation.

3

4

## Capabilities

5

6

### Format Configuration Class

7

8

Main configuration class that controls all aspects of traceback formatting and variable display.

9

10

```python { .api }

11

class Format:

12

def __init__(

13

self,

14

max_value_str_len: int = 1000,

15

ellipsis_rel_pos: float = 0.7,

16

max_exc_str_len: int = 10000,

17

objects_details: int = 1,

18

ellipsis_: str = '...',

19

before: int = 0,

20

after: int = 0,

21

color_scheme: Optional[ColorScheme] = None,

22

skip_files_except: Patterns = None,

23

brief_files_except: Patterns = None,

24

custom_var_printers: Optional[VarPrinters] = None,

25

):

26

"""

27

Configure traceback formatting and variable display options.

28

29

Parameters:

30

- max_value_str_len: Maximum length for variable value strings (default: 1000)

31

- ellipsis_rel_pos: Relative position for ellipsis placement (0.0-1.0, default: 0.7)

32

- max_exc_str_len: Maximum length for exception strings (default: 10000)

33

- objects_details: Depth level for object inspection (default: 1)

34

- ellipsis_: String to use for truncation (default: '...')

35

- before: Number of context lines before exception line (default: 0)

36

- after: Number of context lines after exception line (default: 0)

37

- color_scheme: ColorScheme instance for output styling (default: auto-detect)

38

- skip_files_except: File patterns to skip unless matching (default: None)

39

- brief_files_except: File patterns to show briefly unless matching (default: None)

40

- custom_var_printers: Custom variable printing functions (default: None)

41

"""

42

```

43

44

### Format Instance Methods

45

46

Methods for manipulating and creating Format configurations.

47

48

```python { .api }

49

def replace(self, **kwargs: Dict[str, Any]) -> 'Format':

50

"""

51

Create a new Format instance with specified attributes modified.

52

53

Parameters:

54

- **kwargs: Attribute names and values to override

55

56

Returns:

57

New Format instance with changes applied

58

"""

59

60

@classmethod

61

def add_arguments(cls, parser: argparse.ArgumentParser) -> None:

62

"""

63

Add Format configuration arguments to command-line parser.

64

65

Parameters:

66

- parser: ArgumentParser instance to add arguments to

67

"""

68

69

@classmethod

70

def parse(cls, ns: argparse.Namespace) -> 'Format':

71

"""

72

Create a Format instance from parsed command-line arguments.

73

74

Parameters:

75

- ns: Namespace object from ArgumentParser.parse_args()

76

77

Returns:

78

New Format instance configured from command-line arguments

79

"""

80

81

@classmethod

82

def add_arguments(cls, parser: argparse.ArgumentParser) -> None:

83

"""

84

Add Format configuration arguments to an ArgumentParser.

85

86

Parameters:

87

- parser: ArgumentParser instance to add arguments to

88

"""

89

90

@classmethod

91

def parse(cls, ns: argparse.Namespace) -> 'Format':

92

"""

93

Create Format instance from parsed command-line arguments.

94

95

Parameters:

96

- ns: Parsed arguments namespace

97

98

Returns:

99

Format instance configured from command-line arguments

100

"""

101

```

102

103

### Default Configuration

104

105

Pre-configured Format instance with sensible defaults and security-focused variable hiding.

106

107

```python { .api }

108

default_format: Format

109

"""

110

Default Format instance with built-in security features.

111

112

Automatically hides variables with sensitive names (password, secret, token,

113

key, api_key, credential, pwd) by replacing their values with '...hidden...'.

114

"""

115

116

# Short alias for interactive usage

117

fmt: Format # Alias for default_format

118

```

119

120

## Type Definitions

121

122

```python { .api }

123

# File filtering patterns

124

Patterns = Union[None, str, List[str]]

125

126

# Variable filtering and printing types

127

ShouldPrint = Callable[[str, Type, str, bool], bool] # (name, type, filename, is_global) -> bool

128

VarFilterItem = Union[str, Type, ShouldPrint] # String pattern, type class, or function

129

VarFilter = Union[VarFilterItem, List[VarFilterItem]] # Single filter or list of filters

130

Print = Callable[[Any], Optional[str]] # Custom printer function

131

VarPrinters = List[Tuple[ShouldPrint, Print]] # List of (filter, printer) pairs

132

```

133

134

## Usage Examples

135

136

### Basic Format Configuration

137

138

```python

139

from traceback_with_variables import Format, ColorSchemes, print_exc

140

141

# Create custom format with specific settings

142

custom_format = Format(

143

max_value_str_len=500, # Shorter variable values

144

color_scheme=ColorSchemes.nice, # Use nice color scheme

145

before=2, # Show 2 lines before error

146

after=1, # Show 1 line after error

147

objects_details=2 # Deeper object inspection

148

)

149

150

try:

151

data = {"key": {"nested": {"value": 123}}}

152

result = data["missing"]

153

except Exception as e:

154

print_exc(e, fmt=custom_format)

155

```

156

157

### Variable Filtering and Custom Printing

158

159

```python

160

from traceback_with_variables import Format, hide, skip, print_exc

161

import re

162

163

# Create custom variable printers

164

def custom_printer(obj):

165

if isinstance(obj, dict) and len(obj) > 10:

166

return f"<large dict with {len(obj)} keys>"

167

return None # Use default printing

168

169

# Configure custom variable filtering

170

custom_format = Format(

171

custom_var_printers=[

172

# Hide variables matching sensitive patterns

173

(r'.*(?i:password|secret|token|key|credential).*', hide),

174

175

# Skip displaying large data structures

176

(lambda name, type_, filename, is_global: name.startswith('_temp'), skip),

177

178

# Custom printer for dictionaries

179

(dict, custom_printer),

180

181

# Skip global variables in specific files

182

(lambda name, type_, filename, is_global:

183

is_global and 'test_' in filename, skip),

184

]

185

)

186

187

try:

188

password = "secret123"

189

api_key = "abc123def456"

190

large_dict = {f"key_{i}": i for i in range(100)}

191

_temp_data = [1] * 1000

192

result = 1 / 0

193

except Exception as e:

194

print_exc(e, fmt=custom_format)

195

```

196

197

### File-based Filtering

198

199

```python

200

from traceback_with_variables import Format, print_exc

201

202

# Configure file filtering

203

file_filtered_format = Format(

204

# Only show frames from specific files

205

skip_files_except=[r'.*myproject.*', r'.*main\.py'],

206

207

# Show brief output for these files unless they match above

208

brief_files_except=[r'.*third_party.*', r'.*/__pycache__/.*'],

209

210

max_value_str_len=200

211

)

212

213

try:

214

# Code that involves multiple files

215

import os

216

import json

217

data = json.loads('invalid json')

218

except Exception as e:

219

print_exc(e, fmt=file_filtered_format)

220

```

221

222

### Modifying Existing Formats

223

224

```python

225

from traceback_with_variables import default_format, ColorSchemes

226

227

# Create variations of the default format

228

verbose_format = default_format.replace(

229

before=3,

230

after=2,

231

objects_details=3,

232

max_value_str_len=2000

233

)

234

235

colorful_format = default_format.replace(

236

color_scheme=ColorSchemes.synthwave

237

)

238

239

compact_format = default_format.replace(

240

max_value_str_len=100,

241

objects_details=0,

242

ellipsis_='…'

243

)

244

245

# Use different formats for different scenarios

246

try:

247

debug_data = {"complex": {"nested": {"structure": [1, 2, 3]}}}

248

value = debug_data["missing"]["key"]

249

except Exception as e:

250

print("=== VERBOSE OUTPUT ===")

251

print_exc(e, fmt=verbose_format)

252

253

print("\n=== COMPACT OUTPUT ===")

254

print_exc(e, fmt=compact_format)

255

```

256

257

### Security-focused Configuration

258

259

```python

260

from traceback_with_variables import Format, hide, skip

261

import logging

262

263

# Create security-focused format for production

264

production_format = Format(

265

# Hide all sensitive variables

266

custom_var_printers=[

267

# Comprehensive sensitive data patterns

268

(r'.*(?i:pass|pwd|password|secret|token|key|api|auth|credential|private).*', hide),

269

270

# Skip displaying environment variables

271

(lambda name, type_, filename, is_global:

272

name.startswith('ENV_') or name.startswith('os.environ'), skip),

273

274

# Hide large data structures in production

275

(lambda name, type_, filename, is_global:

276

isinstance(type_, (list, dict)) and name.startswith('cache'), hide),

277

],

278

279

# Shorter output for production logs

280

max_value_str_len=200,

281

max_exc_str_len=5000,

282

objects_details=1,

283

284

# No colors in production logs

285

color_scheme=None

286

)

287

288

# Example usage in production error handler

289

def handle_error(e: Exception):

290

logger = logging.getLogger('production')

291

from traceback_with_variables import LoggerAsFile, print_exc

292

293

logger_file = LoggerAsFile(logger)

294

print_exc(e, fmt=production_format, file_=logger_file)

295

```

296

297

### Command-line Integration

298

299

```python

300

import argparse

301

from traceback_with_variables import Format

302

303

# Set up argument parser with Format options

304

parser = argparse.ArgumentParser()

305

Format.add_arguments(parser)

306

307

# Parse arguments and create format

308

args = parser.parse_args()

309

fmt = Format.parse(args)

310

311

# Use the configured format

312

try:

313

# Your application code here

314

pass

315

except Exception as e:

316

print_exc(e, fmt=fmt)

317

```

318

319

### Interactive Configuration

320

321

```python

322

from traceback_with_variables import default_format as fmt, ColorSchemes

323

324

# Modify the global default format for interactive use

325

fmt.color_scheme = ColorSchemes.synthwave

326

fmt.before = 1

327

fmt.after = 1

328

fmt.max_value_str_len = 300

329

330

# Now all traceback calls will use these settings

331

try:

332

interactive_data = {"session": "active", "user_id": 12345}

333

result = interactive_data["nonexistent"]

334

except Exception as e:

335

print_exc(e) # Uses modified global format

336

```