0
# Dict-like Interface
1
2
The xattr class provides a complete dict-like interface for extended attribute manipulation, allowing natural Python dictionary operations on file extended attributes.
3
4
## Capabilities
5
6
### xattr Class Constructor
7
8
Creates an xattr wrapper for a file path, file descriptor, or file-like object, enabling dict-like access to extended attributes.
9
10
```python { .api }
11
def __init__(self, obj, options=0):
12
"""
13
Create xattr wrapper for extended attribute access.
14
15
Parameters:
16
- obj: str path, int file descriptor, or file-like object with fileno()
17
- options: int, optional flags (XATTR_NOFOLLOW, etc.) OR'd with operation flags
18
19
Returns:
20
xattr instance
21
"""
22
```
23
24
**Usage Examples:**
25
26
```python
27
import xattr
28
29
# From file path
30
x = xattr.xattr('/path/to/file')
31
32
# From file descriptor
33
with open('/path/to/file', 'rb') as f:
34
x = xattr.xattr(f.fileno())
35
36
# From file object
37
with open('/path/to/file', 'rb') as f:
38
x = xattr.xattr(f)
39
40
# With options (don't follow symlinks)
41
x = xattr.xattr('/path/to/symlink', xattr.XATTR_NOFOLLOW)
42
```
43
44
### Attribute Access Methods
45
46
Core methods for reading, writing, and removing extended attributes with optional flags support.
47
48
```python { .api }
49
def get(self, name, options=0, *, default=None):
50
"""
51
Retrieve extended attribute value.
52
53
Parameters:
54
- name: str, attribute name
55
- options: int, operation flags (XATTR_NOFOLLOW, etc.)
56
- default: any, return value if attribute missing (keyword-only)
57
58
Returns:
59
bytes: attribute value
60
61
Raises:
62
IOError: filesystem error or attribute not found (if no default)
63
"""
64
65
def set(self, name, value, options=0):
66
"""
67
Set extended attribute value.
68
69
Parameters:
70
- name: str, attribute name
71
- value: bytes, attribute value (must be bytes)
72
- options: int, operation flags (XATTR_CREATE, XATTR_REPLACE, etc.)
73
74
Raises:
75
IOError: filesystem error, permission denied, or flag constraints
76
TypeError: value is not bytes
77
"""
78
79
def remove(self, name, options=0):
80
"""
81
Remove extended attribute.
82
83
Parameters:
84
- name: str, attribute name
85
- options: int, operation flags (XATTR_NOFOLLOW, etc.)
86
87
Raises:
88
IOError: filesystem error or attribute not found
89
"""
90
91
def list(self, options=0):
92
"""
93
List all extended attribute names.
94
95
Parameters:
96
- options: int, operation flags (XATTR_NOFOLLOW, etc.)
97
98
Returns:
99
list[str]: attribute names with appropriate namespace prefixes
100
101
Raises:
102
IOError: filesystem error
103
"""
104
```
105
106
**Usage Examples:**
107
108
```python
109
x = xattr.xattr('/path/to/file')
110
111
# Get with default
112
description = x.get('user.description', default=b'No description')
113
114
# Set with creation flag
115
x.set('user.title', b'My Document', xattr.XATTR_CREATE)
116
117
# Remove attribute
118
x.remove('user.old_attr')
119
120
# List all attributes
121
attrs = x.list() # ['user.description', 'user.title']
122
```
123
124
### Dictionary Interface
125
126
Complete dict-like methods enabling natural Python dictionary operations on extended attributes.
127
128
```python { .api }
129
# Item access
130
def __getitem__(self, key): ... # x['attr'] -> bytes
131
def __setitem__(self, key, value): ... # x['attr'] = bytes
132
def __delitem__(self, key): ... # del x['attr']
133
134
# Container operations
135
def __len__(self): ... # len(x) -> int
136
def __contains__(self, key): ... # 'attr' in x -> bool
137
def __iter__(self): ... # for attr in x: ...
138
139
# Dictionary methods
140
def keys(self): ... # x.keys() -> list[str]
141
def values(self): ... # x.values() -> list[bytes]
142
def items(self): ... # x.items() -> list[tuple[str, bytes]]
143
def clear(self): ... # x.clear() -> None
144
def copy(self): ... # x.copy() -> dict
145
def update(self, seq): ... # x.update(mapping) -> None
146
def setdefault(self, k, d=''): ... # x.setdefault(key, default) -> bytes
147
148
# Legacy methods
149
def has_key(self, item): ... # x.has_key('attr') -> bool
150
def iterkeys(self): ... # x.iterkeys() -> iterator
151
def itervalues(self): ... # x.itervalues() -> iterator
152
def iteritems(self): ... # x.iteritems() -> iterator
153
```
154
155
**Usage Examples:**
156
157
```python
158
x = xattr.xattr('/path/to/file')
159
160
# Dict-like access
161
x['user.title'] = b'My Document'
162
title = x['user.title'] # b'My Document'
163
del x['user.old_attr']
164
165
# Container operations
166
num_attrs = len(x)
167
if 'user.description' in x:
168
print("Has description")
169
170
# Iteration
171
for attr_name in x:
172
print(f"{attr_name}: {x[attr_name]}")
173
174
# Dictionary methods
175
attrs_dict = dict(x.items()) # {attr_name: attr_value, ...}
176
x.update({'user.author': b'John Doe', 'user.version': b'1.0'})
177
x.clear() # Remove all attributes
178
179
# Get with default
180
description = x.setdefault('user.description', b'Default description')
181
```
182
183
## Error Handling
184
185
Dict-like interface methods raise different exceptions based on operation:
186
187
- **KeyError**: Raised by `__getitem__`, `__delitem__` for missing attributes
188
- **IOError/OSError**: Raised for filesystem errors, permission issues
189
- **TypeError**: Raised when attribute values are not bytes
190
191
```python
192
x = xattr.xattr('/path/to/file')
193
194
try:
195
value = x['nonexistent']
196
except KeyError:
197
print("Attribute does not exist")
198
199
try:
200
x['user.test'] = 'string_value' # Wrong type!
201
except TypeError:
202
print("Values must be bytes")
203
x['user.test'] = b'bytes_value' # Correct
204
```