or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

comments.mdconfiguration.mdcore-printing.mddocument-system.mdextras.mdindex.mdregistration.md

extras.mddocs/

0

# Extras and Extensions

1

2

System for installing and managing third-party library integrations and extensions. The extras system provides specialized pretty printing support for popular Python libraries through a plugin architecture.

3

4

## Capabilities

5

6

### Extras Installation

7

8

Install pretty printing support for third-party libraries through the extras system.

9

10

```python { .api }

11

def install_extras(include=ALL_EXTRAS, *, exclude=frozenset(),

12

raise_on_error=False, warn_on_error=True):

13

"""

14

Install pretty printer extras for third-party libraries.

15

16

Parameters:

17

- include: Iterable of extra names to install (default: all available)

18

- exclude: Iterable of extra names to exclude from installation

19

- raise_on_error (bool): Raise exceptions on import/install failures (default: False)

20

- warn_on_error (bool): Show warnings on import/install failures (default: True)

21

22

Notes:

23

- Automatically handles missing dependencies gracefully

24

- Each extra registers pretty printers for relevant library types

25

- Safe to call multiple times - already installed extras are skipped

26

"""

27

28

ALL_EXTRAS: frozenset

29

"""

30

Set of all available extra names:

31

- 'attrs': Pretty printing for attrs-decorated classes

32

- 'dataclasses': Pretty printing for dataclass instances

33

- 'django': Pretty printing for Django models and querysets

34

- 'ipython': IPython shell integration

35

- 'ipython_repr_pretty': Support for IPython _repr_pretty_ protocol

36

- 'numpy': Pretty printing for NumPy arrays and scalars

37

- 'python': Default Python shell integration

38

- 'requests': Pretty printing for Requests library objects

39

"""

40

```

41

42

## Available Extras

43

44

### attrs Extra

45

46

Pretty printing support for classes created with the attrs library, displaying them as constructor calls with field values.

47

48

**Installation**: Requires `attrs` package

49

**Registration**: Automatic for `@attr.s` decorated classes

50

**Output**: `ClassName(field1=value1, field2=value2)`

51

52

### dataclasses Extra

53

54

Pretty printing support for Python dataclasses, showing them as constructor calls with field values respecting `repr=False` settings.

55

56

**Installation**: Requires `dataclasses` module (Python 3.7+ or backport)

57

**Registration**: Automatic for `@dataclass` decorated classes

58

**Output**: `ClassName(field1=value1, field2=value2)`

59

60

### django Extra

61

62

Pretty printing support for Django models and querysets with intelligent field selection and relationship handling.

63

64

**Installation**: Requires Django framework

65

**Registration**: Automatic for Model and QuerySet subclasses

66

**Output**:

67

- Models: `ModelName(pk=1, field1=value1, field2=value2)`

68

- QuerySets: `<QuerySet [Model1, Model2, ...]>`

69

70

### ipython Extra

71

72

Integration with IPython shells to use prettyprinter as the default pretty printer in IPython environments.

73

74

**Installation**: Requires IPython

75

**Effect**: Replaces IPython's default pretty printing with prettyprinter

76

**Usage**: Automatic in IPython sessions after installation

77

78

### ipython_repr_pretty Extra

79

80

Support for objects that implement IPython's `_repr_pretty_` protocol, enabling integration with IPython's pretty printing system.

81

82

**Installation**: Requires IPython

83

**Registration**: Automatic for objects with `_repr_pretty_` method

84

**Effect**: Uses object's custom `_repr_pretty_` implementation

85

86

### numpy Extra

87

88

Pretty printing support for NumPy arrays and scalars with explicit type information and array structure visualization.

89

90

**Installation**: Requires NumPy

91

**Registration**: Automatic for numpy.ndarray and numpy scalar types

92

**Output**:

93

- Arrays: Structured visualization with shape and dtype info

94

- Scalars: `numpy.int64(42)` style with explicit types

95

96

### python Extra

97

98

Integration with the default Python REPL to use prettyprinter as the default pretty printer.

99

100

**Installation**: No additional dependencies

101

**Effect**: Replaces Python's default pretty printing in REPL

102

**Usage**: Automatic in Python interactive sessions

103

104

### requests Extra

105

106

Pretty printing support for Requests library objects including requests, responses, and sessions.

107

108

**Installation**: Requires requests library

109

**Registration**: Automatic for Request, Response, Session objects

110

**Output**: Structured representation of HTTP objects with key information

111

112

## Usage Examples

113

114

### Basic Extras Installation

115

116

```python

117

from prettyprinter import install_extras, pprint

118

119

# Install all available extras

120

install_extras()

121

122

# Install specific extras only

123

install_extras(include=['numpy', 'requests', 'dataclasses'])

124

125

# Install all except specific extras

126

install_extras(exclude=['django', 'ipython'])

127

128

# Install with error handling

129

install_extras(raise_on_error=True) # Raise on any failures

130

install_extras(warn_on_error=False) # Silent failures

131

```

132

133

### Working with DataClasses

134

135

```python

136

from prettyprinter import install_extras, pprint

137

from dataclasses import dataclass

138

from typing import List, Optional

139

140

# Install dataclasses support

141

install_extras(['dataclasses'])

142

143

@dataclass

144

class User:

145

name: str

146

age: int

147

email: str

148

active: bool = True

149

tags: List[str] = None

150

151

# This field won't appear in output

152

_internal_id: int = 0, repr=False

153

154

@dataclass

155

class Organization:

156

name: str

157

users: List[User]

158

159

user1 = User("Alice", 30, "alice@example.com", tags=["admin", "developer"])

160

user2 = User("Bob", 25, "bob@example.com")

161

org = Organization("Tech Corp", [user1, user2])

162

163

pprint(org)

164

# Organization(

165

# name='Tech Corp',

166

# users=[

167

# User(name='Alice', age=30, email='alice@example.com', active=True, tags=['admin', 'developer']),

168

# User(name='Bob', age=25, email='bob@example.com', active=True, tags=None)

169

# ]

170

# )

171

```

172

173

### Working with NumPy

174

175

```python

176

from prettyprinter import install_extras, pprint

177

import numpy as np

178

179

# Install numpy support

180

install_extras(['numpy'])

181

182

# NumPy arrays

183

array_2d = np.array([[1, 2, 3], [4, 5, 6]])

184

array_large = np.random.random((100, 100))

185

scalar = np.int64(42)

186

187

pprint([array_2d, scalar])

188

# Output shows array structure with dtype information

189

# and explicit scalar types

190

```

191

192

### Working with Requests

193

194

```python

195

from prettyprinter import install_extras, pprint

196

import requests

197

198

# Install requests support

199

install_extras(['requests'])

200

201

# HTTP objects are pretty printed with key information

202

response = requests.get('https://api.github.com/users/octocat')

203

session = requests.Session()

204

session.headers.update({'User-Agent': 'MyApp/1.0'})

205

206

pprint(response)

207

# Shows response status, headers, content info

208

209

pprint(session)

210

# Shows session configuration and state

211

```

212

213

### Working with Django Models

214

215

```python

216

from prettyprinter import install_extras, pprint

217

# Assuming Django is configured

218

219

# Install django support

220

install_extras(['django'])

221

222

# Django models and querysets are automatically handled

223

from myapp.models import User, Post

224

225

user = User.objects.get(id=1)

226

posts = Post.objects.filter(author=user)[:5]

227

228

pprint(user)

229

# User(id=1, username='alice', email='alice@example.com', ...)

230

231

pprint(posts)

232

# <QuerySet [Post(id=1, title='Hello World', ...), ...]>

233

```

234

235

### IPython Integration

236

237

```python

238

from prettyprinter import install_extras

239

240

# Install IPython integration

241

install_extras(['ipython'])

242

243

# Now all IPython pretty printing uses prettyprinter

244

# No additional code needed - works automatically

245

```

246

247

### Custom Extra Development

248

249

```python

250

# Example of creating a custom extra

251

# File: prettyprinter/extras/mylib.py

252

253

from prettyprinter import register_pretty, pretty_call

254

255

def install():

256

"""Install function called by install_extras()."""

257

# Register pretty printers for mylib types

258

pass

259

260

@register_pretty('mylib.MyClass') # Deferred registration

261

def pretty_my_class(obj, ctx):

262

return pretty_call(ctx, type(obj), obj.important_attr)

263

264

# Usage

265

from prettyprinter import install_extras

266

install_extras(['mylib']) # Assumes mylib is in extras directory

267

```

268

269

### Conditional Extras Installation

270

271

```python

272

from prettyprinter import install_extras, ALL_EXTRAS

273

import importlib.util

274

275

def install_available_extras():

276

"""Install only extras for libraries that are available."""

277

available_extras = []

278

279

# Check which libraries are available

280

extra_requirements = {

281

'numpy': 'numpy',

282

'requests': 'requests',

283

'django': 'django',

284

'attrs': 'attr',

285

'ipython': 'IPython'

286

}

287

288

for extra_name, module_name in extra_requirements.items():

289

if importlib.util.find_spec(module_name):

290

available_extras.append(extra_name)

291

292

# Always include these (no external dependencies)

293

available_extras.extend(['python', 'dataclasses', 'ipython_repr_pretty'])

294

295

install_extras(include=available_extras)

296

return available_extras

297

298

# Install only available extras

299

installed = install_available_extras()

300

print(f"Installed extras: {installed}")

301

```

302

303

### Environment-Specific Extras

304

305

```python

306

from prettyprinter import install_extras

307

import os

308

309

def setup_prettyprinter():

310

"""Configure prettyprinter based on environment."""

311

312

base_extras = ['dataclasses', 'python']

313

314

# Development environment

315

if os.getenv('ENV') == 'development':

316

extras = base_extras + ['numpy', 'requests', 'ipython']

317

318

# Jupyter notebook environment

319

elif 'jupyter' in os.getenv('_', '').lower():

320

extras = base_extras + ['numpy', 'ipython', 'ipython_repr_pretty']

321

322

# Django application

323

elif os.getenv('DJANGO_SETTINGS_MODULE'):

324

extras = base_extras + ['django', 'requests']

325

326

# Minimal production environment

327

else:

328

extras = base_extras

329

330

install_extras(include=extras, warn_on_error=False)

331

332

setup_prettyprinter()

333

```

334

335

### Extras Troubleshooting

336

337

```python

338

from prettyprinter import install_extras, ALL_EXTRAS

339

340

def debug_extras_installation():

341

"""Debug extras installation issues."""

342

343

print(f"Available extras: {sorted(ALL_EXTRAS)}")

344

345

# Try installing each extra individually

346

for extra in sorted(ALL_EXTRAS):

347

try:

348

install_extras(include=[extra], raise_on_error=True, warn_on_error=False)

349

print(f"✓ {extra}: installed successfully")

350

except Exception as e:

351

print(f"✗ {extra}: failed - {e}")

352

353

debug_extras_installation()

354

```