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

global-hooks.mddocs/

0

# Global Exception Hooks

1

2

System-level integration that replaces Python's default exception handling with enhanced traceback display. Supports both standard Python environments and IPython/Jupyter notebooks with automatic environment detection and appropriate hook installation.

3

4

## Capabilities

5

6

### Python Global Hook Installation

7

8

Install enhanced exception handling for standard Python environments using sys.excepthook.

9

10

```python { .api }

11

def global_print_exc(fmt: Optional[Format] = None) -> None:

12

"""

13

Install global exception hook for standard Python environments.

14

15

Replaces sys.excepthook to display enhanced tracebacks with variables

16

for all unhandled exceptions.

17

18

Parameters:

19

- fmt: Format configuration (uses default_format if None)

20

21

Usage:

22

global_print_exc() # All unhandled exceptions now show variables

23

"""

24

```

25

26

### IPython/Jupyter Hook Installation

27

28

Install enhanced exception handling specifically for IPython and Jupyter notebook environments.

29

30

```python { .api }

31

def global_print_exc_in_ipython(fmt: Optional[Format] = None) -> None:

32

"""

33

Install global exception hook for IPython/Jupyter environments.

34

35

Replaces IPython.core.interactiveshell.InteractiveShell.showtraceback

36

to display enhanced tracebacks with variables.

37

38

Parameters:

39

- fmt: Format configuration (uses default_format if None)

40

41

Raises:

42

ValueError: If IPython is not available

43

44

Usage:

45

global_print_exc_in_ipython() # All exceptions in IPython show variables

46

"""

47

```

48

49

### Environment Detection

50

51

Functions to detect and handle different Python environments automatically.

52

53

```python { .api }

54

def in_ipython() -> bool:

55

"""

56

Detect if code is running in IPython/Jupyter environment.

57

58

Returns:

59

True if in IPython/Jupyter, False if in standard Python

60

"""

61

62

def is_ipython_global(name: str, type_: Type, filename: str, is_global: bool) -> bool:

63

"""

64

Filter function to identify IPython-specific global variables.

65

66

Identifies IPython built-in variables that should typically be hidden

67

from traceback display (In, Out, get_ipython, exit, quit, _* variables).

68

69

Parameters:

70

- name: Variable name

71

- type_: Variable type

72

- filename: Source file name

73

- is_global: Whether variable is global

74

75

Returns:

76

True if variable is an IPython global that should be filtered

77

"""

78

```

79

80

### Default Hook Configurations

81

82

Pre-configured hook installation functions with sensible defaults for different environments.

83

84

```python { .api }

85

def default_global_print_exc() -> None:

86

"""

87

Install global hook with default settings for standard Python.

88

89

Automatically configures:

90

- Hides global variables by default

91

- Uses standard color scheme detection

92

- Applies security-focused variable filtering

93

"""

94

95

def default_global_print_exc_in_ipython() -> None:

96

"""

97

Install global hook with default settings for IPython/Jupyter.

98

99

Automatically configures:

100

- Hides IPython-specific global variables

101

- Forces common color scheme (suitable for notebooks)

102

- Filters IPython built-ins (In, Out, get_ipython, etc.)

103

"""

104

105

def default_global_print_exc_in_all() -> None:

106

"""

107

Install appropriate global hook based on current environment.

108

109

Automatically detects environment and calls either:

110

- default_global_print_exc_in_ipython() if in IPython/Jupyter

111

- default_global_print_exc() if in standard Python

112

"""

113

```

114

115

## Usage Examples

116

117

### Basic Global Hook Installation

118

119

```python

120

from traceback_with_variables import global_print_exc

121

122

# Install global hook

123

global_print_exc()

124

125

# Now all unhandled exceptions show variables automatically

126

def problematic_function():

127

x = 42

128

y = "hello"

129

return x / 0 # This will show enhanced traceback

130

131

problematic_function() # Enhanced traceback displayed automatically

132

```

133

134

### Custom Format with Global Hook

135

136

```python

137

from traceback_with_variables import global_print_exc, Format, ColorSchemes

138

139

# Create custom format

140

custom_fmt = Format(

141

max_value_str_len=300,

142

color_scheme=ColorSchemes.synthwave,

143

before=1,

144

after=1

145

)

146

147

# Install with custom format

148

global_print_exc(fmt=custom_fmt)

149

150

# All exceptions now use custom formatting

151

data = {"config": {"database": {"host": "localhost"}}}

152

connection = data["config"]["database"]["port"] # Enhanced output with custom format

153

```

154

155

### IPython/Jupyter Integration

156

157

```python

158

from traceback_with_variables import global_print_exc_in_ipython, Format

159

160

# For Jupyter notebooks - install IPython-specific hook

161

try:

162

global_print_exc_in_ipython()

163

print("Enhanced tracebacks enabled for Jupyter!")

164

except ValueError as e:

165

print(f"Not in IPython environment: {e}")

166

167

# Now all cell exceptions show variables with IPython-appropriate formatting

168

notebook_data = {"results": [1, 2, 3, 4, 5]}

169

analysis = notebook_data["missing_data"] # Enhanced traceback in notebook

170

```

171

172

### Automatic Environment Detection

173

174

```python

175

from traceback_with_variables import default_global_print_exc_in_all

176

177

# Automatically detect environment and install appropriate hook

178

default_global_print_exc_in_all()

179

180

# Works correctly in both standard Python and IPython/Jupyter

181

experimental_data = {"trials": 100, "success_rate": 0.85}

182

critical_value = experimental_data["failure_rate"] # Auto-formatted for environment

183

```

184

185

### Auto-activation Imports

186

187

The simplest way to enable enhanced tracebacks globally:

188

189

```python

190

# Auto-activate in any environment (most convenient)

191

import traceback_with_variables.activate_by_import

192

193

# Auto-activate only in standard Python (not Jupyter)

194

import traceback_with_variables.activate_in_python_by_import

195

196

# Auto-activate only in Jupyter/IPython

197

import traceback_with_variables.activate_in_ipython_by_import

198

199

# Ultra-short alias for interactive use

200

import traceback_with_variables.a # Same as activate_by_import

201

```

202

203

### Production-Safe Global Hooks

204

205

```python

206

from traceback_with_variables import global_print_exc, Format, hide, skip

207

import logging

208

import os

209

210

# Create production-safe format

211

production_fmt = Format(

212

# Hide sensitive information

213

custom_var_printers=[

214

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

215

(lambda name, type_, filename, is_global:

216

name.startswith('ENV_'), skip),

217

],

218

219

# Limit verbosity for production logs

220

max_value_str_len=200,

221

objects_details=1,

222

223

# No colors for log files

224

color_scheme=None

225

)

226

227

# Only install in development/debugging mode

228

if os.getenv('DEBUG', '').lower() in ('1', 'true', 'yes'):

229

global_print_exc(fmt=production_fmt)

230

print("Enhanced tracebacks enabled for debugging")

231

else:

232

print("Running in production mode - standard tracebacks")

233

```

234

235

### Temporary Global Hook

236

237

```python

238

from traceback_with_variables import global_print_exc

239

import sys

240

241

# Save original exception hook

242

original_excepthook = sys.excepthook

243

244

# Install enhanced hook temporarily

245

global_print_exc()

246

247

try:

248

# Code that might have exceptions

249

debug_session_data = {"session_id": "abc123", "user": "developer"}

250

process_data = debug_session_data["nonexistent_key"]

251

252

except Exception:

253

pass # Exception shows with variables

254

255

finally:

256

# Restore original hook

257

sys.excepthook = original_excepthook

258

print("Restored original exception handling")

259

```

260

261

### Environment-Specific Configuration

262

263

```python

264

from traceback_with_variables import (

265

in_ipython,

266

global_print_exc,

267

global_print_exc_in_ipython,

268

Format,

269

ColorSchemes

270

)

271

272

# Different configurations for different environments

273

if in_ipython():

274

# Jupyter/IPython: colorful output suitable for notebooks

275

jupyter_fmt = Format(

276

color_scheme=ColorSchemes.nice,

277

max_value_str_len=400,

278

before=1,

279

after=0

280

)

281

global_print_exc_in_ipython(fmt=jupyter_fmt)

282

print("Enhanced Jupyter tracebacks enabled")

283

284

else:

285

# Standard Python: more compact output for terminal

286

terminal_fmt = Format(

287

color_scheme=ColorSchemes.common,

288

max_value_str_len=200,

289

objects_details=1

290

)

291

global_print_exc(fmt=terminal_fmt)

292

print("Enhanced terminal tracebacks enabled")

293

294

# Test the configuration

295

test_data = {"environment": "detected", "config": "applied"}

296

result = test_data["missing"] # Will use appropriate formatting

297

```

298

299

### Module Alias Creation

300

301

```python

302

from traceback_with_variables.tb_alias import create_tb_alias, rm_tb_alias

303

304

# Create filesystem alias for shorter imports

305

try:

306

create_tb_alias()

307

print("Created 'tb' alias - you can now use: import tb")

308

309

# Now you can use: import tb instead of import traceback_with_variables

310

# import tb.activate_by_import # Same as traceback_with_variables.activate_by_import

311

312

except ValueError as e:

313

print(f"Could not create alias: {e}")

314

315

# Remove alias when done

316

try:

317

rm_tb_alias()

318

print("Removed 'tb' alias")

319

except ValueError as e:

320

print(f"Could not remove alias: {e}")

321

```