0
# Advanced Trait Types
1
2
Specialized trait types including class-based types, enums, unions, and network addresses for complex validation scenarios. These provide sophisticated type checking and validation beyond basic Python types.
3
4
## Capabilities
5
6
### Class-Based Types
7
8
Trait types that validate against specific classes or instances.
9
10
#### Base Class for Class-Based Types
11
12
```python { .api }
13
class ClassBasedTraitType(TraitType):
14
"""
15
Base class for Type, Instance, This with string resolution.
16
17
Provides common functionality for trait types that reference
18
classes, including delayed string-based class resolution.
19
"""
20
21
def __init__(self, klass=None, **kwargs):
22
"""
23
Initialize class-based trait.
24
25
Parameters:
26
- klass: type|str|None - Class reference or string name
27
- **kwargs: Additional TraitType parameters
28
"""
29
```
30
31
#### Class Type Validation
32
33
```python { .api }
34
class Type(ClassBasedTraitType):
35
"""
36
Trait whose value must be a subclass of the specified class.
37
38
Validates that assigned values are classes (types) that inherit
39
from the specified base class.
40
"""
41
42
def __init__(self, klass=None, **kwargs):
43
"""
44
Initialize type trait.
45
46
Parameters:
47
- klass: type|str|None - Base class or string name
48
- **kwargs: Additional TraitType parameters
49
"""
50
51
class ForwardDeclaredType(Type):
52
"""
53
Forward-declared version of Type for classes not yet defined.
54
55
Allows referencing classes by string name that will be
56
resolved later when the class becomes available.
57
"""
58
59
def __init__(self, klass=None, **kwargs):
60
"""
61
Initialize forward-declared type trait.
62
63
Parameters:
64
- klass: str - String name of class
65
- **kwargs: Additional TraitType parameters
66
"""
67
```
68
69
#### Instance Type Validation
70
71
```python { .api }
72
class Instance(ClassBasedTraitType):
73
"""
74
Trait whose value must be an instance of the specified class.
75
76
Validates that assigned values are instances of the specified
77
class, with optional automatic instance creation.
78
"""
79
80
def __init__(self, klass=None, args=None, kw=None, **kwargs):
81
"""
82
Initialize instance trait.
83
84
Parameters:
85
- klass: type|str|None - Class or string name
86
- args: tuple|None - Arguments for automatic instance creation
87
- kw: dict|None - Keyword arguments for automatic instance creation
88
- **kwargs: Additional TraitType parameters
89
"""
90
91
class ForwardDeclaredInstance(Instance):
92
"""
93
Forward-declared version of Instance for classes not yet defined.
94
95
Allows referencing classes by string name that will be
96
resolved later when the class becomes available.
97
"""
98
99
def __init__(self, klass=None, args=None, kw=None, **kwargs):
100
"""
101
Initialize forward-declared instance trait.
102
103
Parameters:
104
- klass: str - String name of class
105
- args: tuple|None - Arguments for instance creation
106
- kw: dict|None - Keyword arguments for instance creation
107
- **kwargs: Additional TraitType parameters
108
"""
109
```
110
111
#### Self-Reference Type
112
113
```python { .api }
114
class This(ClassBasedTraitType):
115
"""
116
Trait for instances of the same class as the trait owner.
117
118
Automatically resolves to validate instances of the class
119
that declares this trait.
120
"""
121
122
def __init__(self, **kwargs):
123
"""
124
Initialize self-reference trait.
125
126
Parameters:
127
- **kwargs: Additional TraitType parameters
128
"""
129
```
130
131
### Union Types
132
133
Trait type representing multiple allowed types.
134
135
```python { .api }
136
class Union(TraitType):
137
"""
138
Union type representing multiple allowed trait types.
139
140
Accepts values that validate against any of the specified
141
trait types, trying each in order until one succeeds.
142
"""
143
144
def __init__(self, trait_types, **kwargs):
145
"""
146
Initialize union trait.
147
148
Parameters:
149
- trait_types: list - Sequence of TraitType instances
150
- **kwargs: Additional TraitType parameters
151
"""
152
```
153
154
### Enumeration Types
155
156
Trait types for restricting values to specific choices.
157
158
#### Value-Based Enums
159
160
```python { .api }
161
class Enum(TraitType):
162
"""
163
Enum trait with value from a given sequence.
164
165
Restricts values to those in the specified values sequence,
166
performing exact equality matching.
167
"""
168
169
def __init__(self, values, **kwargs):
170
"""
171
Initialize enum trait.
172
173
Parameters:
174
- values: sequence - Allowed values (list, tuple, set, etc.)
175
- **kwargs: Additional TraitType parameters
176
"""
177
178
class CaselessStrEnum(Enum):
179
"""
180
Case-insensitive string enum.
181
182
Like Enum but performs case-insensitive matching for string values.
183
"""
184
185
def __init__(self, values, **kwargs):
186
"""
187
Initialize case-insensitive string enum trait.
188
189
Parameters:
190
- values: sequence - Allowed string values
191
- **kwargs: Additional TraitType parameters
192
"""
193
```
194
195
#### Python Enum Integration
196
197
```python { .api }
198
class UseEnum(TraitType):
199
"""
200
Trait using a Python Enum class as the model.
201
202
Integrates with Python's enum module, accepting enum members
203
as values and providing enum-specific validation.
204
"""
205
206
def __init__(self, enum_class, **kwargs):
207
"""
208
Initialize enum-based trait.
209
210
Parameters:
211
- enum_class: Enum - Python Enum class to use
212
- **kwargs: Additional TraitType parameters
213
"""
214
```
215
216
### Network Address Types
217
218
Specialized trait types for network addresses.
219
220
```python { .api }
221
class TCPAddress(TraitType):
222
"""
223
Trait for (ip, port) tuple representing TCP addresses.
224
225
Validates 2-tuple with string IP address and integer port.
226
Default value is ('127.0.0.1', 0).
227
"""
228
229
def __init__(self, default_value=('127.0.0.1', 0), **kwargs):
230
"""
231
Initialize TCP address trait.
232
233
Parameters:
234
- default_value: tuple - Default (ip, port) tuple
235
- **kwargs: Additional TraitType parameters
236
"""
237
```
238
239
### Regular Expression Types
240
241
Specialized trait types for compiled regular expressions.
242
243
```python { .api }
244
class CRegExp(TraitType):
245
"""
246
Compiled regular expression trait type.
247
248
Accepts regex pattern strings or compiled regex objects,
249
storing as compiled re.Pattern objects.
250
"""
251
252
def __init__(self, default_value=None, **kwargs):
253
"""
254
Initialize regex trait.
255
256
Parameters:
257
- default_value: str|Pattern|None - Default regex pattern
258
- **kwargs: Additional TraitType parameters
259
"""
260
```
261
262
## Usage Examples
263
264
### Class Type Validation
265
266
```python
267
from traitlets import HasTraits, Type, Instance
268
269
class Animal:
270
pass
271
272
class Dog(Animal):
273
def bark(self):
274
return "Woof!"
275
276
class Cat(Animal):
277
def meow(self):
278
return "Meow!"
279
280
class Pet(HasTraits):
281
animal_type = Type(klass=Animal) # Must be Animal subclass
282
pet = Instance(klass=Animal) # Must be Animal instance
283
284
# Using the trait
285
pet_config = Pet()
286
pet_config.animal_type = Dog # Valid - Dog is subclass of Animal
287
pet_config.pet = Dog() # Valid - Dog() is instance of Animal
288
289
# pet_config.animal_type = Dog() # Would raise TraitError (instance, not class)
290
# pet_config.pet = Dog # Would raise TraitError (class, not instance)
291
```
292
293
### Forward Declaration
294
295
```python
296
from traitlets import HasTraits, ForwardDeclaredInstance
297
298
class TreeNode(HasTraits):
299
# Can reference TreeNode before it's fully defined
300
parent = ForwardDeclaredInstance('TreeNode', allow_none=True)
301
children = List(ForwardDeclaredInstance('TreeNode'))
302
303
root = TreeNode()
304
child = TreeNode(parent=root)
305
root.children = [child]
306
```
307
308
### Self-Reference with This
309
310
```python
311
from traitlets import HasTraits, This, List
312
313
class LinkedListNode(HasTraits):
314
value = Int()
315
next_node = This(allow_none=True) # References same class
316
317
class Tree(HasTraits):
318
children = List(This()) # List of Tree instances
319
320
# Usage
321
node1 = LinkedListNode(value=1)
322
node2 = LinkedListNode(value=2, next_node=node1)
323
324
tree = Tree()
325
subtree1 = Tree()
326
subtree2 = Tree()
327
tree.children = [subtree1, subtree2]
328
```
329
330
### Union Types
331
332
```python
333
from traitlets import HasTraits, Union, Unicode, Int, Float
334
335
class FlexibleData(HasTraits):
336
# Can be string, integer, or float
337
value = Union([Unicode(), Int(), Float()])
338
339
# Can be number or special string values
340
size = Union([Int(min=0), Enum(['auto', 'fill', 'content'])])
341
342
data = FlexibleData()
343
data.value = "hello" # String - valid
344
data.value = 42 # Integer - valid
345
data.value = 3.14 # Float - valid
346
347
data.size = 100 # Integer - valid
348
data.size = "auto" # Enum string - valid
349
# data.size = "invalid" # Would raise TraitError (not in union)
350
```
351
352
### Enumeration Values
353
354
```python
355
from traitlets import HasTraits, Enum, CaselessStrEnum
356
from enum import Enum as PyEnum
357
358
class Priority(PyEnum):
359
LOW = 1
360
MEDIUM = 2
361
HIGH = 3
362
363
class Task(HasTraits):
364
status = Enum(['pending', 'active', 'complete'])
365
theme = CaselessStrEnum(['Light', 'Dark', 'Auto'])
366
priority = UseEnum(Priority)
367
368
task = Task()
369
task.status = 'pending' # Exact match required
370
task.theme = 'light' # Case-insensitive - becomes 'Light'
371
task.theme = 'DARK' # Case-insensitive - becomes 'Dark'
372
task.priority = Priority.HIGH # Enum member
373
374
# task.status = 'PENDING' # Would raise TraitError (case sensitive)
375
# task.priority = 3 # Would raise TraitError (not enum member)
376
```
377
378
### Instance with Auto-Creation
379
380
```python
381
from traitlets import HasTraits, Instance, Unicode
382
383
class DatabaseConfig:
384
def __init__(self, host='localhost', port=5432):
385
self.host = host
386
self.port = port
387
388
class Application(HasTraits):
389
# Automatically creates DatabaseConfig() if none provided
390
db_config = Instance(DatabaseConfig, args=(), kw={'host': 'db.example.com'})
391
392
# Manual instance required
393
logger = Instance('logging.Logger') # String class name
394
395
app = Application()
396
print(app.db_config.host) # 'db.example.com' (auto-created)
397
print(app.db_config.port) # 5432 (auto-created)
398
399
import logging
400
app.logger = logging.getLogger('app') # Must set manually
401
```
402
403
### Complex Union Example
404
405
```python
406
from traitlets import HasTraits, Union, Instance, Unicode, Int, List
407
408
class ConfigValue(HasTraits):
409
# Can be single value or list of values
410
# Each value can be string, int, or a nested ConfigValue
411
value = Union([
412
Unicode(), # Simple string
413
Int(), # Simple integer
414
Instance('ConfigValue'), # Nested config
415
List(Unicode()), # List of strings
416
List(Int()), # List of integers
417
List(Instance('ConfigValue')) # List of nested configs
418
])
419
420
# Various valid assignments
421
config = ConfigValue()
422
config.value = "simple string" # String
423
config.value = 42 # Integer
424
config.value = ["list", "of", "strings"] # String list
425
config.value = [1, 2, 3] # Integer list
426
427
# Nested configuration
428
nested = ConfigValue()
429
nested.value = "nested value"
430
config.value = nested # Single nested
431
432
config.value = [ConfigValue(), ConfigValue()] # List of nested
433
```