0
# Constants Reference
1
2
pyparted provides extensive constants for device types, partition types, flags, units, and other enumerated values. These constants ensure type safety and provide readable code.
3
4
## Capabilities
5
6
### Unit Constants
7
8
Constants for size and unit specifications used throughout the library.
9
10
```python { .api }
11
# Sector-based units
12
UNIT_SECTOR: int # Sectors
13
UNIT_BYTE: int # Bytes
14
UNIT_CYLINDER: int # Cylinders
15
UNIT_CHS: int # Cylinder-Head-Sector
16
UNIT_PERCENT: int # Percentage
17
UNIT_COMPACT: int # Compact display
18
19
# SI units (decimal, base 1000)
20
UNIT_KILOBYTE: int # Kilobytes (1,000 bytes)
21
UNIT_MEGABYTE: int # Megabytes (1,000,000 bytes)
22
UNIT_GIGABYTE: int # Gigabytes (1,000,000,000 bytes)
23
UNIT_TERABYTE: int # Terabytes (1,000,000,000,000 bytes)
24
25
# IEC units (binary, base 1024)
26
UNIT_KIBIBYTE: int # Kibibytes (1,024 bytes)
27
UNIT_MEBIBYTE: int # Mebibytes (1,048,576 bytes)
28
UNIT_GIBIBYTE: int # Gibibytes (1,073,741,824 bytes)
29
UNIT_TEBIBYTE: int # Tebibytes (1,099,511,627,776 bytes)
30
```
31
32
### Device Type Constants
33
34
Constants identifying different storage device interface types.
35
36
```python { .api }
37
DEVICE_UNKNOWN: int # Unknown device type
38
DEVICE_SCSI: int # SCSI devices
39
DEVICE_IDE: int # IDE/PATA devices
40
DEVICE_DAC960: int # DAC960 RAID controller
41
DEVICE_CPQARRAY: int # Compaq Smart Array
42
DEVICE_FILE: int # File-based devices (disk images)
43
DEVICE_ATARAID: int # ATA RAID devices
44
DEVICE_I2O: int # I2O devices
45
DEVICE_UBD: int # User-mode block devices
46
DEVICE_DASD: int # S/390 DASD devices
47
DEVICE_VIODASD: int # Virtual I/O DASD
48
DEVICE_SX8: int # Promise SX8 devices
49
DEVICE_DM: int # Device mapper devices
50
DEVICE_XVD: int # Xen virtual devices
51
DEVICE_SDMMC: int # SD/MMC devices
52
DEVICE_VIRTBLK: int # Virtual block devices
53
DEVICE_NVME: int # NVMe devices
54
```
55
56
### Partition Type Constants
57
58
Constants defining the basic type and role of partitions.
59
60
```python { .api }
61
PARTITION_NORMAL: int # Regular primary partition
62
PARTITION_LOGICAL: int # Logical partition (within extended)
63
PARTITION_EXTENDED: int # Extended partition container
64
PARTITION_FREESPACE: int # Free space region (not a real partition)
65
PARTITION_METADATA: int # Metadata partition (system use)
66
PARTITION_PROTECTED: int # Protected partition (system use)
67
```
68
69
### Partition Flag Constants
70
71
Constants for partition flags that control partition behavior and properties.
72
73
```python { .api }
74
# Basic flags
75
PARTITION_BOOT: int # Boot/active flag
76
PARTITION_ROOT: int # Root filesystem flag
77
PARTITION_SWAP: int # Swap partition flag
78
PARTITION_HIDDEN: int # Hidden partition flag
79
PARTITION_RAID: int # Software RAID member
80
PARTITION_LVM: int # LVM physical volume
81
PARTITION_LBA: int # LBA addressing required
82
83
# System-specific flags
84
PARTITION_HPSERVICE: int # HP service partition
85
PARTITION_PALO: int # PA-RISC boot partition
86
PARTITION_PREP: int # PowerPC PReP boot partition
87
PARTITION_DIAG: int # Diagnostic partition
88
PARTITION_LEGACY_BOOT: int # Legacy boot flag
89
90
# UEFI/GPT flags
91
PARTITION_ESP: int # EFI System Partition
92
PARTITION_BIOS_GRUB: int # BIOS boot partition for GRUB
93
PARTITION_APPLE_TV_RECOVERY: int # Apple TV recovery partition
94
95
# Microsoft flags
96
PARTITION_MSFT_RESERVED: int # Microsoft Reserved partition
97
PARTITION_MSFT_DATA: int # Microsoft Basic Data partition (conditional)
98
PARTITION_IRST: int # Intel Rapid Start Technology (conditional)
99
100
# Chrome OS flags
101
PARTITION_CHROMEOS_KERNEL: int # Chrome OS kernel partition (conditional)
102
103
# Linux-specific flags
104
PARTITION_BLS_BOOT: int # Boot Loader Specification boot (conditional)
105
PARTITION_LINUX_HOME: int # Linux home partition (conditional)
106
PARTITION_NO_AUTOMOUNT: int # No auto-mount flag (conditional)
107
PARTITION_NONFS: int # Non-filesystem partition (conditional)
108
```
109
110
### Disk Flag Constants
111
112
Constants for disk-level flags affecting entire partition tables.
113
114
```python { .api }
115
DISK_CYLINDER_ALIGNMENT: int # Cylinder alignment flag
116
DISK_GPT_PMBR_BOOT: int # GPT protective MBR boot flag
117
```
118
119
### Disk Type Feature Constants
120
121
Constants for querying disk type capabilities and features.
122
123
```python { .api }
124
DISK_TYPE_EXTENDED: int # Supports extended partitions
125
DISK_TYPE_PARTITION_NAME: int # Supports partition names
126
DISK_TYPE_PARTITION_TYPE_ID: int # Supports partition type IDs (conditional)
127
DISK_TYPE_PARTITION_TYPE_UUID: int # Supports partition type UUIDs (conditional)
128
DISK_TYPE_DISK_UUID: int # Supports disk UUIDs (conditional)
129
DISK_TYPE_PARTITION_UUID: int # Supports partition UUIDs (conditional)
130
```
131
132
### Exception Type Constants
133
134
Constants for categorizing exception severity levels.
135
136
```python { .api }
137
EXCEPTION_TYPE_INFORMATION: int # Informational message
138
EXCEPTION_TYPE_WARNING: int # Warning message
139
EXCEPTION_TYPE_ERROR: int # Error condition
140
EXCEPTION_TYPE_FATAL: int # Fatal error
141
EXCEPTION_TYPE_BUG: int # Software bug detected
142
EXCEPTION_TYPE_NO_FEATURE: int # Feature not supported
143
```
144
145
### Exception Resolution Constants
146
147
Constants for exception handling and resolution options.
148
149
```python { .api }
150
EXCEPTION_RESOLVE_UNHANDLED: int # Exception not handled
151
EXCEPTION_RESOLVE_FIX: int # Fix the problem
152
EXCEPTION_RESOLVE_YES: int # Yes response
153
EXCEPTION_RESOLVE_NO: int # No response
154
EXCEPTION_RESOLVE_OK: int # OK response
155
EXCEPTION_RESOLVE_RETRY: int # Retry operation
156
EXCEPTION_RESOLVE_IGNORE: int # Ignore the problem
157
EXCEPTION_RESOLVE_CANCEL: int # Cancel operation
158
```
159
160
### Exception Option Constants
161
162
Constants for available exception response options.
163
164
```python { .api }
165
EXCEPTION_OPT_OK_CANCEL: int # OK/Cancel options
166
EXCEPTION_OPT_YES_NO: int # Yes/No options
167
EXCEPTION_OPT_YES_NO_CANCEL: int # Yes/No/Cancel options
168
EXCEPTION_OPT_IGNORE_CANCEL: int # Ignore/Cancel options
169
EXCEPTION_OPT_RETRY_CANCEL: int # Retry/Cancel options
170
EXCEPTION_OPT_RETRY_IGNORE_CANCEL: int # Retry/Ignore/Cancel options
171
```
172
173
## Global Dictionaries
174
175
pyparted provides dictionaries that map constants to human-readable names.
176
177
```python { .api }
178
# Unit mappings
179
units: dict[int, str] # Maps unit constants to names
180
181
# Device type mappings
182
devices: dict[int, str] # Maps device type constants to names
183
184
# Partition mappings
185
partitions: dict[int, str] # Maps partition constants to names
186
187
# Type registries
188
diskType: dict[str, object] # Available disk types
189
fileSystemType: dict[str, object] # Available filesystem types
190
diskFlag: dict[str, int] # Available disk flags
191
partitionFlag: dict[str, int] # Available partition flags
192
```
193
194
## Usage Examples
195
196
### Working with Device Types
197
198
```python
199
import parted
200
201
device = parted.getDevice('/dev/sda')
202
203
# Check device type using constants
204
if device.type == parted.DEVICE_SCSI:
205
print("SCSI device")
206
elif device.type == parted.DEVICE_NVME:
207
print("NVMe device")
208
elif device.type == parted.DEVICE_VIRTBLK:
209
print("Virtual block device")
210
else:
211
print(f"Other device type: {device.type}")
212
213
# Use dictionary for readable output
214
device_name = parted.devices.get(device.type, "Unknown")
215
print(f"Device type: {device_name}")
216
217
# List all known device types
218
print("\nAll device types:")
219
for type_const, type_name in parted.devices.items():
220
print(f" {type_name}: {type_const}")
221
```
222
223
### Working with Partition Types and Flags
224
225
```python
226
import parted
227
228
device = parted.getDevice('/dev/sda')
229
disk = parted.newDisk(device)
230
231
for partition in disk.partitions:
232
# Check partition type
233
if partition.type == parted.PARTITION_NORMAL:
234
type_name = "Primary"
235
elif partition.type == parted.PARTITION_LOGICAL:
236
type_name = "Logical"
237
elif partition.type == parted.PARTITION_EXTENDED:
238
type_name = "Extended"
239
else:
240
type_name = f"Other ({partition.type})"
241
242
print(f"Partition {partition.number}: {type_name}")
243
244
# Check common flags
245
flags_set = []
246
flag_checks = [
247
(parted.PARTITION_BOOT, "boot"),
248
(parted.PARTITION_SWAP, "swap"),
249
(parted.PARTITION_RAID, "raid"),
250
(parted.PARTITION_LVM, "lvm"),
251
(parted.PARTITION_ESP, "esp")
252
]
253
254
for flag_const, flag_name in flag_checks:
255
if partition.isFlagAvailable(flag_const) and partition.getFlag(flag_const):
256
flags_set.append(flag_name)
257
258
if flags_set:
259
print(f" Flags: {', '.join(flags_set)}")
260
```
261
262
### Working with Units
263
264
```python
265
import parted
266
267
# Display all available units
268
print("Available units:")
269
for unit_const, unit_name in parted.units.items():
270
print(f" {unit_name}: {unit_const}")
271
272
# Use unit constants for calculations
273
device = parted.getDevice('/dev/sda')
274
device_bytes = device.length * device.sectorSize
275
276
# Convert to different units using constants
277
size_gb = parted.formatBytes(device_bytes, 'GB')
278
size_gib = parted.formatBytes(device_bytes, 'GiB')
279
280
print(f"Device size: {size_gb:.1f} GB ({size_gib:.1f} GiB)")
281
```
282
283
### Checking Disk Type Features
284
285
```python
286
import parted
287
288
device = parted.getDevice('/dev/sda')
289
disk = parted.newDisk(device)
290
291
# Check what features the disk type supports
292
features_to_check = [
293
(parted.DISK_TYPE_EXTENDED, "Extended partitions"),
294
(parted.DISK_TYPE_PARTITION_NAME, "Partition names")
295
]
296
297
# Add conditional features if available
298
if hasattr(parted, 'DISK_TYPE_PARTITION_UUID'):
299
features_to_check.append((parted.DISK_TYPE_PARTITION_UUID, "Partition UUIDs"))
300
301
if hasattr(parted, 'DISK_TYPE_DISK_UUID'):
302
features_to_check.append((parted.DISK_TYPE_DISK_UUID, "Disk UUIDs"))
303
304
print(f"Disk type: {disk.type}")
305
print("Supported features:")
306
307
for feature_const, feature_name in features_to_check:
308
supported = disk.supportsFeature(feature_const)
309
status = "✓" if supported else "✗"
310
print(f" {status} {feature_name}")
311
```
312
313
### Flag Availability Checking
314
315
```python
316
import parted
317
318
device = parted.getDevice('/dev/sda')
319
disk = parted.newDisk(device)
320
partition = disk.getPartitionByNumber(1)
321
322
if partition:
323
print(f"Partition {partition.number} flag availability:")
324
325
# Check all partition flags
326
all_flags = [
327
(parted.PARTITION_BOOT, "boot"),
328
(parted.PARTITION_ROOT, "root"),
329
(parted.PARTITION_SWAP, "swap"),
330
(parted.PARTITION_HIDDEN, "hidden"),
331
(parted.PARTITION_RAID, "raid"),
332
(parted.PARTITION_LVM, "lvm"),
333
(parted.PARTITION_LBA, "lba"),
334
(parted.PARTITION_ESP, "esp"),
335
(parted.PARTITION_BIOS_GRUB, "bios_grub"),
336
(parted.PARTITION_PREP, "prep"),
337
(parted.PARTITION_MSFT_RESERVED, "msft_reserved")
338
]
339
340
# Add conditional flags if available
341
if hasattr(parted, 'PARTITION_MSFT_DATA'):
342
all_flags.append((parted.PARTITION_MSFT_DATA, "msft_data"))
343
344
for flag_const, flag_name in all_flags:
345
available = partition.isFlagAvailable(flag_const)
346
if available:
347
current_value = partition.getFlag(flag_const)
348
status = "ON" if current_value else "off"
349
print(f" ✓ {flag_name}: {status}")
350
else:
351
print(f" ✗ {flag_name}: not available")
352
```
353
354
### Using Exception Constants
355
356
```python
357
import parted
358
359
def custom_exception_handler(exception_type, message, options):
360
"""Custom exception handler using constants."""
361
362
# Determine exception type
363
if exception_type == parted.EXCEPTION_TYPE_INFORMATION:
364
print(f"INFO: {message}")
365
return parted.EXCEPTION_RESOLVE_OK
366
elif exception_type == parted.EXCEPTION_TYPE_WARNING:
367
print(f"WARNING: {message}")
368
return parted.EXCEPTION_RESOLVE_OK
369
elif exception_type == parted.EXCEPTION_TYPE_ERROR:
370
print(f"ERROR: {message}")
371
372
# Check available options
373
if options == parted.EXCEPTION_OPT_YES_NO:
374
response = input("Continue? (y/n): ")
375
return parted.EXCEPTION_RESOLVE_YES if response.lower() == 'y' else parted.EXCEPTION_RESOLVE_NO
376
elif options == parted.EXCEPTION_OPT_RETRY_CANCEL:
377
response = input("Retry? (r/c): ")
378
return parted.EXCEPTION_RESOLVE_RETRY if response.lower() == 'r' else parted.EXCEPTION_RESOLVE_CANCEL
379
380
return parted.EXCEPTION_RESOLVE_UNHANDLED
381
382
# Register the handler
383
parted.register_exn_handler(custom_exception_handler)
384
```
385
386
### Constant Validation
387
388
```python
389
import parted
390
391
def validate_constants():
392
"""Validate that expected constants exist."""
393
required_constants = [
394
'DEVICE_SCSI', 'DEVICE_NVME', 'DEVICE_VIRTBLK',
395
'PARTITION_NORMAL', 'PARTITION_LOGICAL', 'PARTITION_EXTENDED',
396
'PARTITION_BOOT', 'PARTITION_SWAP', 'PARTITION_ESP',
397
'UNIT_SECTOR', 'UNIT_GIGABYTE', 'UNIT_GIBIBYTE'
398
]
399
400
missing = []
401
for const_name in required_constants:
402
if not hasattr(parted, const_name):
403
missing.append(const_name)
404
405
if missing:
406
print(f"Missing constants: {missing}")
407
return False
408
else:
409
print("All required constants available")
410
return True
411
412
# Check optional constants
413
def check_optional_constants():
414
"""Check for optional/conditional constants."""
415
optional_constants = [
416
'PARTITION_MSFT_DATA',
417
'PARTITION_CHROMEOS_KERNEL',
418
'PARTITION_BLS_BOOT',
419
'DISK_TYPE_PARTITION_UUID'
420
]
421
422
print("Optional constants:")
423
for const_name in optional_constants:
424
available = hasattr(parted, const_name)
425
status = "✓" if available else "✗"
426
print(f" {status} {const_name}")
427
428
validate_constants()
429
check_optional_constants()
430
```
431
432
## Architecture-Specific Constants
433
434
Some constants may not be available on all systems or may have conditional availability:
435
436
### Conditional Constants
437
- `PARTITION_MSFT_DATA` - Available on systems with newer libparted
438
- `PARTITION_IRST` - Intel Rapid Start Technology support
439
- `PARTITION_CHROMEOS_KERNEL` - Chrome OS kernel partition
440
- `DISK_TYPE_PARTITION_UUID` - GPT partition UUID support
441
442
### Best Practices
443
444
1. **Use hasattr()**: Check constant availability before use
445
2. **Meaningful Names**: Constants provide better readability than magic numbers
446
3. **Type Safety**: Constants prevent typos in numeric values
447
4. **Future Compatibility**: Constants adapt to library changes
448
5. **Documentation**: Constants are self-documenting code