0
# Utilities and Aliases
1
2
Utility functions and module aliasing system for enhanced convenience and integration. Includes filesystem-based module aliases for shorter imports and ANSI color code utilities.
3
4
## Capabilities
5
6
### Module Aliasing System
7
8
Create filesystem-based aliases for shorter and more convenient module imports.
9
10
```python { .api }
11
def create_alias(alias: str, module_name: str) -> None:
12
"""
13
Create a filesystem alias for a module to enable shorter imports.
14
15
Creates a symbolic link in the module's parent directory that points
16
to the original module, allowing import via the shorter alias name.
17
18
Parameters:
19
- alias: Short name for the alias (must be valid Python identifier)
20
- module_name: Full name of the module to alias
21
22
Raises:
23
- ValueError: If alias is empty, contains invalid characters, or conflicts
24
- FileExistsError: If filesystem location is already occupied
25
26
Requirements:
27
- Alias must contain only ASCII lowercase letters, digits, and underscores
28
- Module must exist and be importable
29
- Filesystem must support symbolic links
30
"""
31
32
def rm_alias(alias: str) -> None:
33
"""
34
Remove a previously created module alias.
35
36
Removes the symbolic link created by create_alias, restoring the
37
filesystem to its original state.
38
39
Parameters:
40
- alias: Name of the alias to remove
41
42
Raises:
43
- ValueError: If the module is not an alias (not a symbolic link)
44
- ModuleNotFoundError: If the alias doesn't exist
45
"""
46
47
def module_name_to_path(name: str) -> Path:
48
"""
49
Convert a module name to its filesystem path.
50
51
Uses importlib to find the module's location and returns the
52
appropriate path (directory for packages, file for modules).
53
54
Parameters:
55
- name: Module name to locate
56
57
Returns:
58
Path object pointing to the module's location
59
60
Raises:
61
ModuleNotFoundError: If the module cannot be found
62
"""
63
64
def module_exists(name: str) -> bool:
65
"""
66
Check if a module exists and can be imported.
67
68
Parameters:
69
- name: Module name to check
70
71
Returns:
72
True if module exists, False otherwise
73
"""
74
```
75
76
### Traceback-with-Variables Specific Aliases
77
78
Convenience functions for creating and managing the 'tb' alias for traceback-with-variables.
79
80
```python { .api }
81
def create_tb_alias() -> None:
82
"""
83
Create 'tb' alias for traceback-with-variables module.
84
85
Allows using 'import tb' instead of 'import traceback_with_variables'
86
for more convenient interactive usage.
87
88
Equivalent to: create_alias('tb', 'traceback_with_variables')
89
90
Raises:
91
ValueError: If alias creation fails
92
"""
93
94
def rm_tb_alias() -> None:
95
"""
96
Remove the 'tb' alias for traceback-with-variables.
97
98
Removes the symbolic link created by create_tb_alias.
99
100
Equivalent to: rm_alias('tb')
101
102
Raises:
103
ValueError: If alias removal fails
104
"""
105
```
106
107
### ANSI Color Utilities
108
109
Low-level utilities for working with ANSI color codes.
110
111
```python { .api }
112
def to_ansi(str_: str) -> str:
113
"""
114
Convert a color code string to a complete ANSI escape sequence.
115
116
Takes a color code (e.g., '31' for red, '32;1' for bright green)
117
and wraps it in the appropriate ANSI escape sequence format.
118
119
Parameters:
120
- str_: ANSI color code string (e.g., '31', '32;1', '38;2;255;0;0')
121
122
Returns:
123
Complete ANSI escape sequence (e.g., '\033[31m') or empty string if input is empty
124
125
Examples:
126
- to_ansi('31') -> '\033[31m' # Red
127
- to_ansi('32;1') -> '\033[32;1m' # Bright green
128
- to_ansi('') -> '' # No color
129
"""
130
```
131
132
## Usage Examples
133
134
### Creating Module Aliases
135
136
```python
137
from traceback_with_variables.module_alias import create_alias, rm_alias
138
139
# Create a short alias for a long module name
140
try:
141
create_alias('np', 'numpy')
142
print("Created 'np' alias for numpy")
143
144
# Now you can use: import np
145
# Instead of: import numpy as np
146
147
except ValueError as e:
148
print(f"Failed to create alias: {e}")
149
150
# Remove the alias when done
151
try:
152
rm_alias('np')
153
print("Removed 'np' alias")
154
except ValueError as e:
155
print(f"Failed to remove alias: {e}")
156
```
157
158
### Traceback-with-Variables Alias
159
160
```python
161
from traceback_with_variables.tb_alias import create_tb_alias, rm_tb_alias
162
163
# Create convenient 'tb' alias
164
try:
165
create_tb_alias()
166
print("Created 'tb' alias - you can now use shorter imports!")
167
168
# Now you can use:
169
# import tb # Instead of: import traceback_with_variables
170
# import tb.activate_by_import # Instead of: import traceback_with_variables.activate_by_import
171
# from tb import print_exc, Format # Instead of: from traceback_with_variables import print_exc, Format
172
# tb.print_exc(exception) # Instead of: traceback_with_variables.print_exc(exception)
173
174
except ValueError as e:
175
print(f"Could not create tb alias: {e}")
176
177
# Example usage with alias
178
try:
179
import tb
180
181
# Use the alias for enhanced tracebacks
182
def test_function():
183
data = {"key": "value"}
184
return data["missing"]
185
186
try:
187
test_function()
188
except Exception as e:
189
tb.print_exc(e) # Much shorter than traceback_with_variables.print_exc(e)
190
191
finally:
192
# Clean up alias
193
try:
194
rm_tb_alias()
195
print("Removed 'tb' alias")
196
except ValueError:
197
pass
198
```
199
200
### Interactive Development with Aliases
201
202
```python
203
from traceback_with_variables.tb_alias import create_tb_alias
204
205
# Set up for interactive session
206
try:
207
create_tb_alias()
208
209
# Ultra-convenient interactive usage
210
import tb.activate_by_import # Auto-activate enhanced tracebacks
211
from tb import Format, ColorSchemes # Import commonly used classes
212
213
# Set up interactive-friendly format
214
interactive_fmt = Format(
215
color_scheme=ColorSchemes.nice,
216
max_value_str_len=200,
217
before=1,
218
after=0
219
)
220
221
# Use throughout interactive session
222
try:
223
interactive_data = {"session": "active", "user": "developer"}
224
result = interactive_data["nonexistent"]
225
except Exception as e:
226
tb.print_exc(e, fmt=interactive_fmt)
227
228
except ValueError as e:
229
print(f"Alias setup failed: {e}")
230
# Fall back to full module name
231
import traceback_with_variables.activate_by_import
232
```
233
234
### Module Existence Checking
235
236
```python
237
from traceback_with_variables.module_alias import module_exists, module_name_to_path
238
239
# Check if modules exist before creating aliases
240
modules_to_alias = {
241
'np': 'numpy',
242
'pd': 'pandas',
243
'plt': 'matplotlib.pyplot',
244
'tb': 'traceback_with_variables'
245
}
246
247
for alias, module_name in modules_to_alias.items():
248
if module_exists(module_name):
249
try:
250
create_alias(alias, module_name)
251
module_path = module_name_to_path(module_name)
252
print(f"Created alias '{alias}' -> '{module_name}' (at {module_path})")
253
except ValueError as e:
254
print(f"Could not create alias '{alias}': {e}")
255
else:
256
print(f"Module '{module_name}' not available, skipping alias '{alias}'")
257
```
258
259
### Custom ANSI Color Creation
260
261
```python
262
from traceback_with_variables.color import to_ansi, ColorScheme
263
264
# Create custom colors using to_ansi utility
265
def create_custom_color_scheme():
266
"""Create a custom color scheme using ANSI utilities."""
267
return ColorScheme(
268
common=to_ansi('0'), # Normal
269
file_=to_ansi('34'), # Blue
270
line_num=to_ansi('33'), # Yellow
271
func_name=to_ansi('35'), # Magenta
272
func_snippet=to_ansi('37'), # White
273
name=to_ansi('36'), # Cyan
274
value=to_ansi('32'), # Green
275
exc_class=to_ansi('31;1'), # Bright red
276
exc_text=to_ansi('31'), # Red
277
end=to_ansi('0') # Reset
278
)
279
280
# Create RGB color scheme (for terminals that support it)
281
def create_rgb_color_scheme():
282
"""Create an RGB color scheme using 24-bit color codes."""
283
return ColorScheme(
284
common=to_ansi('38;2;200;200;200'), # Light gray
285
file_=to_ansi('38;2;100;150;255'), # Light blue
286
line_num=to_ansi('38;2;255;200;100'), # Orange
287
func_name=to_ansi('38;2;255;100;200'), # Pink
288
func_snippet=to_ansi('38;2;150;255;150'), # Light green
289
name=to_ansi('38;2;200;100;255'), # Purple
290
value=to_ansi('38;2;100;255;200'), # Cyan
291
exc_class=to_ansi('38;2;255;100;100'), # Light red
292
exc_text=to_ansi('38;2;255;150;150'), # Lighter red
293
end=to_ansi('0') # Reset
294
)
295
296
# Use custom color schemes
297
from traceback_with_variables import Format, print_exc
298
299
custom_fmt = Format(color_scheme=create_custom_color_scheme())
300
rgb_fmt = Format(color_scheme=create_rgb_color_scheme())
301
302
try:
303
test_data = {"colors": ["red", "green", "blue"]}
304
missing_color = test_data["missing_colors"]
305
except Exception as e:
306
print("=== Custom Color Scheme ===")
307
print_exc(e, fmt=custom_fmt)
308
309
print("\n=== RGB Color Scheme ===")
310
print_exc(e, fmt=rgb_fmt)
311
```
312
313
### Alias Management Utilities
314
315
```python
316
from traceback_with_variables.module_alias import create_alias, rm_alias, module_exists
317
import os
318
319
class AliasManager:
320
"""Utility class for managing multiple module aliases."""
321
322
def __init__(self):
323
self.aliases = {}
324
325
def create_alias_safe(self, alias: str, module_name: str) -> bool:
326
"""Safely create an alias with error handling."""
327
if not module_exists(module_name):
328
print(f"Module '{module_name}' not found")
329
return False
330
331
try:
332
create_alias(alias, module_name)
333
self.aliases[alias] = module_name
334
print(f"Created alias: '{alias}' -> '{module_name}'")
335
return True
336
except ValueError as e:
337
print(f"Could not create alias '{alias}': {e}")
338
return False
339
340
def remove_all_aliases(self):
341
"""Remove all created aliases."""
342
for alias in list(self.aliases.keys()):
343
try:
344
rm_alias(alias)
345
print(f"Removed alias: '{alias}'")
346
del self.aliases[alias]
347
except ValueError as e:
348
print(f"Could not remove alias '{alias}': {e}")
349
350
def list_aliases(self):
351
"""List all active aliases."""
352
if not self.aliases:
353
print("No active aliases")
354
else:
355
print("Active aliases:")
356
for alias, module in self.aliases.items():
357
print(f" '{alias}' -> '{module}'")
358
359
# Usage
360
manager = AliasManager()
361
362
# Create commonly used aliases
363
manager.create_alias_safe('tb', 'traceback_with_variables')
364
manager.create_alias_safe('np', 'numpy')
365
manager.create_alias_safe('pd', 'pandas')
366
367
# List what was created
368
manager.list_aliases()
369
370
# Use the aliases
371
try:
372
import tb
373
tb.activate_by_import # Auto-activate enhanced tracebacks
374
except ImportError:
375
print("tb alias not available")
376
377
# Clean up when done
378
manager.remove_all_aliases()
379
```
380
381
### Platform-Specific Alias Handling
382
383
```python
384
import sys
385
import os
386
from traceback_with_variables.module_alias import create_alias, rm_alias
387
388
def create_platform_safe_alias(alias: str, module_name: str) -> bool:
389
"""Create alias with platform-specific error handling."""
390
391
if sys.platform == 'win32':
392
# Windows may not support symbolic links without admin privileges
393
try:
394
create_alias(alias, module_name)
395
return True
396
except (OSError, PermissionError) as e:
397
print(f"Windows alias creation failed (may need admin rights): {e}")
398
return False
399
else:
400
# Unix-like systems generally support symbolic links
401
try:
402
create_alias(alias, module_name)
403
return True
404
except ValueError as e:
405
print(f"Unix alias creation failed: {e}")
406
return False
407
408
# Platform-aware alias creation
409
if create_platform_safe_alias('tb', 'traceback_with_variables'):
410
print("Successfully created 'tb' alias")
411
412
# Use the alias
413
import tb.activate_by_import
414
415
# Clean up
416
try:
417
rm_alias('tb')
418
except ValueError:
419
pass
420
else:
421
print("Using full module name instead of alias")
422
import traceback_with_variables.activate_by_import
423
```