0
# Configuration and Utilities
1
2
Configuration management through profiles, path utilities for IPython directories, system information functions, and various utility classes for IPython development and customization.
3
4
## Capabilities
5
6
### Path and Directory Utilities
7
8
Functions for managing IPython directories and locating configuration files.
9
10
```python { .api }
11
def get_ipython_dir():
12
"""
13
Get the IPython directory path.
14
15
Returns the path to the main IPython configuration directory.
16
Typically ~/.ipython on Unix systems.
17
18
Returns:
19
str: Path to IPython directory
20
"""
21
22
def get_ipython_cache_dir():
23
"""
24
Get the IPython cache directory path.
25
26
Returns the path to IPython's cache directory for temporary files,
27
compiled files, and other cached data.
28
29
Returns:
30
str: Path to IPython cache directory
31
"""
32
33
def get_ipython_package_dir():
34
"""
35
Get the IPython package installation directory.
36
37
Returns the path where the IPython package is installed,
38
useful for locating built-in resources and extensions.
39
40
Returns:
41
str: Path to IPython package directory
42
"""
43
44
def get_ipython_module_path(module_str):
45
"""
46
Get the path to an IPython module.
47
48
Parameters:
49
- module_str: str - Module name (e.g., 'IPython.core.magic')
50
51
Returns:
52
str: Path to module file
53
"""
54
55
def locate_profile(profile='default'):
56
"""
57
Find a profile directory by name.
58
59
Searches for an IPython profile directory and returns its path.
60
Creates the profile directory if it doesn't exist.
61
62
Parameters:
63
- profile: str - Profile name (default: 'default')
64
65
Returns:
66
str: Path to profile directory
67
"""
68
```
69
70
Usage examples:
71
72
```python
73
from IPython.paths import *
74
75
# Get IPython directories
76
ipython_dir = get_ipython_dir()
77
print(f"IPython config dir: {ipython_dir}")
78
79
cache_dir = get_ipython_cache_dir()
80
print(f"Cache dir: {cache_dir}")
81
82
# Locate profile directories
83
default_profile = locate_profile() # Uses 'default' profile
84
custom_profile = locate_profile('myprofile')
85
86
# Get package paths
87
package_dir = get_ipython_package_dir()
88
magic_module = get_ipython_module_path('IPython.core.magic')
89
```
90
91
### System Information
92
93
Functions for gathering system and environment information.
94
95
```python { .api }
96
def sys_info():
97
"""
98
Get comprehensive system information.
99
100
Returns detailed information about the Python environment,
101
IPython installation, system platform, and dependencies.
102
Useful for debugging and support requests.
103
104
Returns:
105
dict: System information including:
106
- IPython version and path
107
- Python version and executable
108
- Operating system details
109
- Key dependency versions
110
- Environment variables
111
"""
112
```
113
114
Usage example:
115
116
```python
117
from IPython.utils.sysinfo import sys_info
118
119
# Get system information
120
info = sys_info()
121
print("System Information:")
122
for key, value in info.items():
123
print(f" {key}: {value}")
124
125
# Access specific information
126
print(f"IPython version: {info['ipython_version']}")
127
print(f"Python executable: {info['sys_executable']}")
128
```
129
130
### Frame and Inspection Utilities
131
132
Utilities for working with Python call frames and extracting context information.
133
134
```python { .api }
135
def extract_module_locals(depth=0):
136
"""
137
Extract module and local variables from the call stack.
138
139
Examines the call stack at the specified depth and extracts
140
the module and local namespace, useful for embedding and
141
context-aware operations.
142
143
Parameters:
144
- depth: int - Stack depth to examine (0 = current frame)
145
146
Returns:
147
tuple: (module, locals_dict) where module is the Python module
148
and locals_dict contains local variables
149
"""
150
```
151
152
Usage example:
153
154
```python
155
from IPython.utils.frame import extract_module_locals
156
157
def my_function():
158
local_var = "test data"
159
160
# Extract current context
161
module, locals_dict = extract_module_locals(0)
162
print(f"Module: {module}")
163
print(f"Local variables: {list(locals_dict.keys())}")
164
165
# Extract caller's context
166
caller_module, caller_locals = extract_module_locals(1)
167
return module, locals_dict
168
169
my_function()
170
```
171
172
### Clipboard Utilities
173
174
Utilities for clipboard integration and data transfer.
175
176
```python { .api }
177
def tkinter_clipboard_get():
178
"""
179
Get clipboard contents using tkinter.
180
181
Returns:
182
str: Clipboard text content
183
"""
184
185
def osx_clipboard_get():
186
"""
187
Get clipboard contents on macOS using pbpaste.
188
189
Returns:
190
str: Clipboard text content
191
"""
192
193
def win32_clipboard_get():
194
"""
195
Get clipboard contents on Windows.
196
197
Returns:
198
str: Clipboard text content
199
"""
200
201
def clipboard_get():
202
"""
203
Get clipboard contents (cross-platform).
204
205
Automatically detects platform and uses appropriate method.
206
207
Returns:
208
str: Clipboard text content
209
"""
210
```
211
212
### Background Jobs
213
214
Utilities for running background jobs and processes.
215
216
```python { .api }
217
class BackgroundJobManager:
218
"""
219
Manager for background jobs and processes.
220
221
Allows running long-running tasks in the background
222
while keeping the IPython shell interactive.
223
"""
224
225
def __init__(self):
226
"""Initialize background job manager."""
227
228
def new(self, func_or_code, *args, **kwargs):
229
"""
230
Start a new background job.
231
232
Parameters:
233
- func_or_code: callable or str - Function or code to execute
234
- *args, **kwargs: Arguments for function
235
236
Returns:
237
BackgroundJob: Job object for monitoring
238
"""
239
240
class BackgroundJob:
241
"""Individual background job."""
242
243
def __init__(self, func, *args, **kwargs):
244
"""Initialize background job."""
245
246
def start(self):
247
"""Start the background job."""
248
249
def is_alive(self):
250
"""Check if job is still running."""
251
252
def kill(self):
253
"""Terminate the background job."""
254
```
255
256
### Data Structure Utilities
257
258
Enhanced data structures for IPython development.
259
260
```python { .api }
261
class Struct:
262
"""
263
Enhanced dictionary that allows attribute access to items.
264
265
A dictionary-like object that supports both dict['key'] and
266
dict.key access patterns. Useful for configuration objects
267
and structured data.
268
"""
269
270
def __init__(self, **kwargs):
271
"""
272
Initialize Struct with keyword arguments.
273
274
Parameters:
275
- **kwargs: initial key-value pairs
276
"""
277
278
def __getattr__(self, key):
279
"""Get item as attribute."""
280
281
def __setattr__(self, key, value):
282
"""Set item as attribute."""
283
284
def __getitem__(self, key):
285
"""Get item using dict syntax."""
286
287
def __setitem__(self, key, value):
288
"""Set item using dict syntax."""
289
290
def __contains__(self, key):
291
"""Check if key exists."""
292
293
def keys(self):
294
"""Return keys."""
295
296
def values(self):
297
"""Return values."""
298
299
def items(self):
300
"""Return key-value pairs."""
301
```
302
303
Usage example:
304
305
```python
306
from IPython.utils.ipstruct import Struct
307
308
# Create struct with initial data
309
config = Struct(
310
debug=True,
311
max_items=100,
312
output_format='json'
313
)
314
315
# Access using attribute notation
316
print(config.debug) # True
317
config.debug = False
318
319
# Access using dict notation
320
print(config['max_items']) # 100
321
config['new_option'] = 'value'
322
323
# Use like a regular dict
324
for key, value in config.items():
325
print(f"{key}: {value}")
326
```
327
328
### Pretty Printing Utilities
329
330
Advanced pretty printing for complex data structures.
331
332
```python { .api }
333
def pretty(obj, verbose=False, max_width=79, newline=True, max_seq_length=1000):
334
"""
335
Pretty print an object.
336
337
Parameters:
338
- obj: object to pretty print
339
- verbose: bool - Include more detail
340
- max_width: int - Maximum line width
341
- newline: bool - Add newline at end
342
- max_seq_length: int - Maximum sequence length to print
343
344
Returns:
345
str: Pretty printed representation
346
"""
347
348
def pprint(obj, verbose=False, max_width=79, newline=True, max_seq_length=1000):
349
"""
350
Pretty print and display an object.
351
352
Same as pretty() but prints the result instead of returning it.
353
"""
354
355
class PrettyPrinter:
356
"""
357
Configurable pretty printer for complex data structures.
358
359
Provides fine-grained control over pretty printing behavior,
360
including custom formatting for specific types.
361
"""
362
363
def __init__(self, output, max_width=79, newline=True, max_seq_length=1000):
364
"""Initialize pretty printer with output stream."""
365
366
def pretty(self, obj):
367
"""Pretty print object to configured output."""
368
```
369
370
Usage example:
371
372
```python
373
from IPython.lib.pretty import pretty, pprint, PrettyPrinter
374
import sys
375
376
# Simple pretty printing
377
data = {'users': [{'name': 'Alice', 'scores': [95, 87, 92]},
378
{'name': 'Bob', 'scores': [78, 82, 88]}]}
379
380
print(pretty(data))
381
pprint(data) # Prints directly
382
383
# Custom pretty printer
384
printer = PrettyPrinter(sys.stdout, max_width=60)
385
printer.pretty(data)
386
```
387
388
### Configuration Classes
389
390
Configuration management for IPython components.
391
392
```python { .api }
393
# Base configuration classes use traitlets
394
from traitlets import Bool, Int, Unicode, List
395
from IPython.core.configurable import Configurable
396
397
class BaseConfig(Configurable):
398
"""Base configuration class for IPython components."""
399
400
enabled = Bool(True, help="Enable this component").tag(config=True)
401
debug = Bool(False, help="Enable debug mode").tag(config=True)
402
403
# Common configuration patterns
404
class ShellConfig(BaseConfig):
405
"""Configuration for interactive shell."""
406
colors = Unicode('Linux', help="Color scheme").tag(config=True)
407
autoindent = Bool(True, help="Auto-indent code").tag(config=True)
408
history_length = Int(10000, help="History length").tag(config=True)
409
410
class DisplayConfig(BaseConfig):
411
"""Configuration for display system."""
412
max_width = Int(79, help="Maximum display width").tag(config=True)
413
show_repr = Bool(True, help="Show object repr").tag(config=True)
414
```
415
416
## Types
417
418
```python { .api }
419
class Struct(dict):
420
"""
421
Enhanced dictionary with attribute access.
422
423
Combines dictionary functionality with attribute access,
424
making it useful for configuration objects and structured data.
425
"""
426
427
def __init__(self, **kwargs):
428
"""Initialize with keyword arguments."""
429
430
def __getattr__(self, key):
431
"""Get attribute."""
432
433
def __setattr__(self, key, value):
434
"""Set attribute."""
435
436
class PrettyPrinter:
437
"""
438
Configurable pretty printer.
439
440
Provides advanced pretty printing with customizable formatting
441
and support for complex nested data structures.
442
"""
443
444
def __init__(self, output, max_width=79, newline=True):
445
"""Initialize printer with output configuration."""
446
447
def pretty(self, obj):
448
"""Pretty print object."""
449
450
# Path and directory types
451
PathType = str # File system paths
452
ProfileName = str # IPython profile names
453
ModulePath = str # Python module paths
454
```