0
# Container Trait Types
1
2
Container trait types for Python collections including lists, dictionaries, sets, and tuples. These types provide element type validation, size constraints, and change notifications for collection-based attributes.
3
4
## Capabilities
5
6
### Base Container Class
7
8
Foundation class for all container trait types.
9
10
```python { .api }
11
class Container(Instance):
12
"""
13
Base class for container trait types.
14
15
Provides common functionality for collections including element
16
type validation and change notification setup.
17
"""
18
19
def __init__(self, trait=None, default_value=Undefined, **kwargs):
20
"""
21
Initialize container trait.
22
23
Parameters:
24
- trait: TraitType|None - Element type validator
25
- default_value: any - Default container value
26
- **kwargs: Additional TraitType parameters
27
"""
28
```
29
30
### List Types
31
32
List trait types with element validation and size constraints.
33
34
```python { .api }
35
class List(Container):
36
"""
37
Python list trait type with element validation.
38
39
Validates list values with optional element type checking
40
and size constraints. Default value is empty list [].
41
"""
42
43
def __init__(self, trait=None, default_value=Undefined, minlen=0, maxlen=sys.maxsize, **kwargs):
44
"""
45
Initialize list trait.
46
47
Parameters:
48
- trait: TraitType|None - Element type for validation
49
- default_value: list - Default list value ([] if Undefined, None if not specified)
50
- minlen: int - Minimum list length
51
- maxlen: int - Maximum list length
52
- **kwargs: Additional TraitType parameters
53
"""
54
```
55
56
### Set Types
57
58
Set trait types for unordered collections of unique elements.
59
60
```python { .api }
61
class Set(List):
62
"""
63
Python set trait type with element validation.
64
65
Validates set values with optional element type checking
66
and size constraints. Default value is empty set set().
67
"""
68
69
def __init__(self, trait=None, default_value=Undefined, minlen=0, maxlen=sys.maxsize, **kwargs):
70
"""
71
Initialize set trait.
72
73
Parameters:
74
- trait: TraitType|None - Element type for validation
75
- default_value: set - Default set value (set() if Undefined, None if not specified)
76
- minlen: int - Minimum set length
77
- maxlen: int - Maximum set length
78
- **kwargs: Additional TraitType parameters
79
"""
80
```
81
82
### Tuple Types
83
84
Tuple trait types for immutable sequences with fixed or variable element types.
85
86
```python { .api }
87
class Tuple(TraitType):
88
"""
89
Python tuple trait type with element validation.
90
91
Supports both fixed-length tuples with per-element type
92
validation and variable-length tuples with homogeneous elements.
93
"""
94
95
def __init__(self, *traits, **kwargs):
96
"""
97
Initialize tuple trait.
98
99
Can be used in two modes:
100
1. Fixed-length: Tuple(Int(), Unicode(), Bool()) - exactly 3 elements
101
2. Variable-length: Tuple(default_value=()) - any length tuple
102
103
Parameters:
104
- *traits: TraitType instances for fixed-length validation
105
- default_value: tuple - Default tuple value (overrides traits mode)
106
- **kwargs: Additional TraitType parameters
107
"""
108
```
109
110
### Dictionary Types
111
112
Dictionary trait types with key and value validation.
113
114
```python { .api }
115
class Dict(TraitType):
116
"""
117
Python dict trait type with key/value validation.
118
119
Supports validation of dictionary values with optional per-key
120
type specification or uniform value type validation.
121
"""
122
123
def __init__(self, trait=None, traits=None, default_value=Undefined, **kwargs):
124
"""
125
Initialize dict trait.
126
127
Can be used in three modes:
128
1. Uniform values: Dict(Unicode()) - all values must be unicode
129
2. Per-key types: Dict(traits={'name': Unicode(), 'age': Int()})
130
3. Unvalidated: Dict() - any dict structure allowed
131
132
Parameters:
133
- trait: TraitType|None - Uniform value type validator
134
- traits: dict|None - Per-key type validators {key: TraitType}
135
- default_value: dict - Default dict value ({} if Undefined)
136
- **kwargs: Additional TraitType parameters
137
"""
138
```
139
140
141
## Usage Examples
142
143
### List with Element Validation
144
145
```python
146
from traitlets import HasTraits, List, Unicode, Int
147
148
class TodoList(HasTraits):
149
items = List(Unicode()) # List of strings
150
priorities = List(Int(min=1, max=5)) # List of priority numbers 1-5
151
tags = List(minlen=1) # List with at least 1 element
152
153
todo = TodoList()
154
todo.items = ["Buy milk", "Walk dog", "Write code"]
155
todo.priorities = [2, 1, 3]
156
todo.tags = ["urgent"]
157
158
# todo.items = [123, 456] # Would raise TraitError (not strings)
159
# todo.priorities = [0, 6] # Would raise TraitError (out of range)
160
# todo.tags = [] # Would raise TraitError (too short)
161
```
162
163
### Dictionary with Type Validation
164
165
```python
166
from traitlets import HasTraits, Dict, Unicode, Int, Bool
167
168
class UserProfile(HasTraits):
169
metadata = Dict(Unicode()) # Dict with string values
170
settings = Dict(traits={ # Dict with specific key types
171
'theme': Unicode(),
172
'notifications': Bool(),
173
'max_items': Int(min=1)
174
})
175
data = Dict() # Any dict structure
176
177
user = UserProfile()
178
user.metadata = {'role': 'admin', 'department': 'engineering'}
179
user.settings = {
180
'theme': 'dark',
181
'notifications': True,
182
'max_items': 50
183
}
184
user.data = {'scores': [1, 2, 3], 'nested': {'key': 'value'}}
185
186
# user.metadata = {'count': 123} # Would raise TraitError (value not string)
187
# user.settings = {'theme': 123} # Would raise TraitError (theme not string)
188
```
189
190
### Tuple with Fixed Types
191
192
```python
193
from traitlets import HasTraits, Tuple, Unicode, Int, Float
194
195
class Coordinate(HasTraits):
196
point_2d = Tuple(Float(), Float()) # (x, y) coordinates
197
point_3d = Tuple(Float(), Float(), Float()) # (x, y, z) coordinates
198
labeled_point = Tuple(Unicode(), Float(), Float()) # (label, x, y)
199
200
coord = Coordinate()
201
coord.point_2d = (1.5, 2.7)
202
coord.point_3d = (1.0, 2.0, 3.0)
203
coord.labeled_point = ("center", 0.0, 0.0)
204
205
# coord.point_2d = (1.0, 2.0, 3.0) # Would raise TraitError (wrong length)
206
# coord.point_3d = ("x", "y", "z") # Would raise TraitError (not floats)
207
```
208
209
### Set with Element Validation
210
211
```python
212
from traitlets import HasTraits, Set, Unicode
213
214
class TaggedItem(HasTraits):
215
tags = Set(Unicode(), minlen=1, maxlen=10) # 1-10 unique string tags
216
217
item = TaggedItem()
218
item.tags = {"python", "programming", "tutorial"}
219
220
# Automatically removes duplicates
221
item.tags = {"python", "python", "code"} # Becomes {"python", "code"}
222
223
# item.tags = set() # Would raise TraitError (too short)
224
# item.tags = {1, 2, 3} # Would raise TraitError (not strings)
225
```
226
227
### TCP Address Validation
228
229
```python
230
from traitlets import HasTraits, TCPAddress
231
232
class Server(HasTraits):
233
bind_address = TCPAddress()
234
proxy_address = TCPAddress(('192.168.1.100', 8080))
235
236
server = Server()
237
server.bind_address = ('0.0.0.0', 3000)
238
print(server.proxy_address) # ('192.168.1.100', 8080)
239
240
# server.bind_address = ('localhost', '3000') # Would raise TraitError (port not int)
241
# server.bind_address = ('host', 80, 'extra') # Would raise TraitError (wrong length)
242
```
243
244
### Regular Expression Patterns
245
246
```python
247
import re
248
from traitlets import HasTraits, CRegExp
249
250
class Validator(HasTraits):
251
email_pattern = CRegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
252
phone_pattern = CRegExp()
253
254
validator = Validator()
255
# Can set as string pattern
256
validator.phone_pattern = r'^\d{3}-\d{3}-\d{4}$'
257
258
# Or as compiled regex
259
validator.phone_pattern = re.compile(r'^\(\d{3}\) \d{3}-\d{4}$')
260
261
# Access compiled pattern
262
if validator.email_pattern.match('user@example.com'):
263
print("Valid email")
264
```
265
266
### Variable-Length Tuples
267
268
```python
269
from traitlets import HasTraits, Tuple
270
271
class FlexibleData(HasTraits):
272
coordinates = Tuple() # Any length tuple
273
rgb_color = Tuple(default_value=(255, 255, 255)) # Default white
274
275
data = FlexibleData()
276
data.coordinates = (1, 2) # 2D point
277
data.coordinates = (1, 2, 3) # 3D point
278
data.coordinates = (1, 2, 3, 4) # 4D point
279
280
print(data.rgb_color) # (255, 255, 255)
281
```