or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# IceCream

1

2

Never use print() to debug again; inspect variables, expressions, and program execution with a single, simple function call. IceCream (ic) makes print debugging 60% faster to type, automatically displays variable names and values, and provides syntax highlighting and contextual information.

3

4

## Package Information

5

6

- **Package Name**: icecream

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install icecream`

10

11

## Core Imports

12

13

```python

14

from icecream import ic

15

```

16

17

Additional imports:

18

19

```python

20

from icecream import (

21

ic, # Main debug function

22

install, uninstall, # Global installation

23

argumentToString, # Custom type formatting

24

stderrPrint, # Utility function for stderr output

25

IceCreamDebugger # Main debugger class

26

)

27

```

28

29

For global installation (optional):

30

31

```python

32

from icecream import install

33

install()

34

# Now ic() is available globally without import

35

```

36

37

## Basic Usage

38

39

```python

40

from icecream import ic

41

42

# Simple variable inspection

43

x = 42

44

ic(x) # Output: ic| x: 42

45

46

# Expression inspection

47

def calculate(a, b):

48

return a * b + 10

49

50

result = ic(calculate(5, 3)) # Output: ic| calculate(5, 3): 25

51

print(result) # 25 (ic returns the value)

52

53

# Execution tracking (no arguments)

54

def process_data():

55

ic() # Output: ic| example.py:12 in process_data()

56

# ... processing code

57

ic() # Output: ic| example.py:15 in process_data()

58

59

# Multiple arguments

60

name = "Alice"

61

age = 30

62

ic(name, age) # Output: ic| name: 'Alice', age: 30

63

64

# Complex data structures

65

data = {'users': [1, 2, 3], 'status': 'active'}

66

ic(data)

67

# Output: ic| data: {'users': [1, 2, 3], 'status': 'active'}

68

```

69

70

## Capabilities

71

72

### Core Debugging Function

73

74

The main debugging function that automatically prints variable names and values with syntax highlighting.

75

76

```python { .api }

77

def ic(*args):

78

"""

79

Debug function that prints variable names and values.

80

81

Parameters:

82

- *args: Any number of variables, expressions, or values to inspect

83

84

Returns:

85

- None if no arguments provided

86

- Single value if one argument provided

87

- Tuple of values if multiple arguments provided

88

89

Examples:

90

- ic() prints execution context (filename, line, function)

91

- ic(x) prints "ic| x: <value>" and returns x

92

- ic(x, y) prints "ic| x: <value>, y: <value>" and returns (x, y)

93

"""

94

```

95

96

### Output Formatting

97

98

Get formatted debug output as a string instead of printing to stderr.

99

100

```python { .api }

101

def format(*args) -> str:

102

"""

103

Returns formatted debug output as string.

104

105

Parameters:

106

- *args: Variables or expressions to format

107

108

Returns:

109

- str: Formatted debug output string

110

"""

111

```

112

113

### Output Control

114

115

Enable and disable debug output while preserving return values.

116

117

```python { .api }

118

def enable() -> None:

119

"""Enable debug output (enabled by default)."""

120

121

def disable() -> None:

122

"""Disable debug output while maintaining return values."""

123

```

124

125

### Output Configuration

126

127

Customize output formatting, destination, and behavior.

128

129

```python { .api }

130

def configureOutput(

131

prefix=_absent,

132

outputFunction=_absent,

133

argToStringFunction=_absent,

134

includeContext=_absent,

135

contextAbsPath=_absent,

136

lineWrapWidth=_absent

137

) -> None:

138

"""

139

Configure debug output formatting and behavior.

140

141

Parameters:

142

- prefix (str or callable, optional): Custom output prefix (default: 'ic| ')

143

- outputFunction (callable, optional): Custom output function (default: colorized stderr print)

144

- argToStringFunction (callable, optional): Custom string conversion function (default: argumentToString)

145

- includeContext (bool, optional): Include filename/line/function info (default: False)

146

- contextAbsPath (bool, optional): Use absolute paths in context (default: False)

147

- lineWrapWidth (int, optional): Max line width before wrapping (default: 70)

148

149

Raises:

150

- TypeError: If no parameters are provided

151

152

Note: All parameters are optional. Only provided parameters will be updated.

153

"""

154

```

155

156

### Global Installation

157

158

Install ic() function globally as a builtin for use without imports.

159

160

```python { .api }

161

def install(ic='ic') -> None:

162

"""

163

Install ic() globally as builtin function.

164

165

Parameters:

166

- ic (str): Name to install as (default: 'ic')

167

"""

168

169

def uninstall(ic='ic') -> None:

170

"""

171

Remove globally installed ic() function.

172

173

Parameters:

174

- ic (str): Name to remove (default: 'ic')

175

"""

176

```

177

178

### Custom Type Formatting

179

180

Register custom string conversion functions for specific types using single dispatch.

181

182

```python { .api }

183

@functools.singledispatch

184

def argumentToString(obj) -> str:

185

"""

186

Convert object to string representation for debug output.

187

Uses pprint.pformat() by default with fallback to repr().

188

189

Parameters:

190

- obj: Object to convert to string

191

192

Returns:

193

- str: String representation of the object

194

195

Attributes:

196

- registry: mappingproxy showing registered type formatters

197

- register: Method to register formatters for specific types

198

- unregister: Method to remove registered formatters (added dynamically)

199

"""

200

201

@argumentToString.register(YourCustomType)

202

def _(obj: YourCustomType) -> str:

203

"""Register custom formatter for YourCustomType."""

204

return f"CustomType({obj})"

205

206

# Access the registry property

207

argumentToString.registry # mappingproxy of registered formatters

208

209

# Unregister a type (method added dynamically by custom singledispatch)

210

argumentToString.unregister(YourCustomType) # Remove custom formatter

211

```

212

213

### Utility Functions

214

215

Lower-level functions available for advanced usage.

216

217

```python { .api }

218

def stderrPrint(*args) -> None:

219

"""

220

Print arguments to stderr.

221

222

Parameters:

223

- *args: Arguments to print to stderr

224

"""

225

226

def colorize(s: str) -> str:

227

"""

228

Apply syntax highlighting to string using Pygments.

229

230

Parameters:

231

- s (str): String to colorize

232

233

Returns:

234

- str: Colorized string with ANSI escape codes

235

"""

236

```

237

238

### Constants

239

240

Configuration constants available for reference.

241

242

```python { .api }

243

DEFAULT_PREFIX: str = 'ic| ' # Default output prefix

244

DEFAULT_LINE_WRAP_WIDTH: int = 70 # Default line wrap width

245

DEFAULT_CONTEXT_DELIMITER: str = '- ' # Context delimiter

246

DEFAULT_OUTPUT_FUNCTION: callable # Default colorized stderr print

247

DEFAULT_ARG_TO_STRING_FUNCTION: callable # Default argumentToString function

248

NO_SOURCE_AVAILABLE_WARNING_MESSAGE: str # Warning when source unavailable

249

```

250

251

## Advanced Usage Examples

252

253

### Custom Prefix and Context

254

255

```python

256

from icecream import ic

257

258

# Custom prefix with timestamp

259

import time

260

def timestamp():

261

return f'{int(time.time())} |> '

262

263

ic.configureOutput(prefix=timestamp, includeContext=True)

264

ic('debugging')

265

# Output: 1519185860 |> example.py:8 in <module>- 'debugging': 'debugging'

266

```

267

268

### Custom Output Function

269

270

```python

271

import logging

272

from icecream import ic

273

274

# Log debug output instead of printing

275

def log_debug(s):

276

logging.warning(s)

277

278

ic.configureOutput(outputFunction=log_debug)

279

ic('logged message')

280

# Sends to Python logging system instead of stderr

281

```

282

283

### Custom Type Formatting

284

285

```python

286

from icecream import ic, argumentToString

287

import numpy as np

288

289

# Register numpy array formatter

290

@argumentToString.register(np.ndarray)

291

def _(obj):

292

return f"ndarray(shape={obj.shape}, dtype={obj.dtype})"

293

294

x = np.zeros((10, 5))

295

ic(x) # Output: ic| x: ndarray(shape=(10, 5), dtype=float64)

296

```

297

298

### Graceful Fallback

299

300

```python

301

# Fallback for production environments

302

try:

303

from icecream import ic

304

except ImportError:

305

ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a)

306

```

307

308

## Types

309

310

```python { .api }

311

class IceCreamDebugger:

312

"""

313

Main debugger class. The global 'ic' instance is created from this class.

314

315

Attributes:

316

- enabled (bool): Controls whether output is printed (default: True)

317

- prefix (str | callable): Output prefix (default: 'ic| ')

318

- includeContext (bool): Include filename/line/function info (default: False)

319

- outputFunction (callable): Function to handle output (default: colorized stderr)

320

- argToStringFunction (callable): Function to convert args to strings (default: argumentToString)

321

- contextAbsPath (bool): Use absolute paths in context (default: False)

322

- lineWrapWidth (int): Max line width before wrapping (default: 70)

323

- contextDelimiter (str): Delimiter between context and arguments (default: '- ')

324

- _pairDelimiter (str): Delimiter between argument pairs (default: ', ')

325

"""

326

327

def __init__(

328

self,

329

prefix: str | callable = DEFAULT_PREFIX,

330

outputFunction: callable = DEFAULT_OUTPUT_FUNCTION,

331

argToStringFunction: callable = argumentToString,

332

includeContext: bool = False,

333

contextAbsPath: bool = False

334

): ...

335

336

def __call__(self, *args):

337

"""

338

Main debug function. Prints variables and returns them.

339

340

Parameters:

341

- *args: Variables or expressions to debug

342

343

Returns:

344

- None if no arguments

345

- Single value if one argument

346

- Tuple if multiple arguments

347

"""

348

349

def format(self, *args) -> str:

350

"""Return formatted debug output as string instead of printing."""

351

352

def enable(self) -> None:

353

"""Enable debug output."""

354

355

def disable(self) -> None:

356

"""Disable debug output while preserving return values."""

357

358

def configureOutput(

359

self,

360

prefix=_absent,

361

outputFunction=_absent,

362

argToStringFunction=_absent,

363

includeContext=_absent,

364

contextAbsPath=_absent,

365

lineWrapWidth=_absent

366

) -> None:

367

"""Configure output settings. See configureOutput() function for details."""

368

```

369

370

## Error Handling

371

372

IceCream handles various edge cases gracefully:

373

374

- **Missing source code**: Issues `RuntimeWarning` and shows values only when source code cannot be accessed (REPL sessions, frozen applications like PyInstaller, or when source changes during execution)

375

- **Complex objects**: Falls back to `repr()` if `pprint.pformat()` fails due to comparison issues

376

- **Large outputs**: Automatically wraps long lines based on `lineWrapWidth` setting

377

- **Import errors**: Use graceful fallback pattern for production environments

378

- **Configuration errors**: Raises `TypeError` if `configureOutput()` called with no parameters

379

380

### Warning Messages

381

382

When IceCream cannot access source code, it issues this warning:

383

384

```python { .api }

385

NO_SOURCE_AVAILABLE_WARNING_MESSAGE: str = (

386

'Failed to access the underlying source code for analysis. Was ic() '

387

'invoked in a REPL (e.g. from the command line), a frozen application '

388

'(e.g. packaged with PyInstaller), or did the underlying source code '

389

'change during execution?'

390

)

391

```

392

393

The warning is issued as a `RuntimeWarning` with `stacklevel=4` to point to the actual `ic()` call location.

394

395

## Version Information

396

397

Package metadata constants available for import:

398

399

```python { .api }

400

__version__: str # Package version (e.g., '2.1.7')

401

__title__: str # Package name ('icecream')

402

__author__: str # Author name ('Ansgar Grunseid')

403

__license__: str # License type ('MIT')

404

__contact__: str # Author email ('grunseid@gmail.com')

405

__url__: str # Project URL ('https://github.com/gruns/icecream')

406

__description__: str # Package description

407

```

408

409

```python

410

from icecream import __version__, __author__

411

print(f"IceCream v{__version__} by {__author__}")

412

```

413

414

## Dependencies

415

416

- **colorama** (>=0.3.9): Cross-platform colored terminal text

417

- **pygments** (>=2.2.0): Syntax highlighting

418

- **executing** (>=2.1.0): AST analysis for variable name detection

419

- **asttokens** (>=2.0.1): AST token mapping for source code analysis

420

421

## Python Compatibility

422

423

- Python 3.8+

424

- PyPy3

425

- Cross-platform support (Windows, macOS, Linux)