0
# Basic Trait Types
1
2
Fundamental trait types for common Python data types including integers, floats, strings, booleans, and complex numbers. These types provide validation, coercion, and constraint checking for basic Python values.
3
4
## Capabilities
5
6
### Numeric Types
7
8
#### Integer Types
9
10
Integer trait types with optional bounds validation.
11
12
```python { .api }
13
class Int(TraitType):
14
"""
15
Integer trait type with optional min/max bounds.
16
17
Validates that values are integers within specified range.
18
Default value is 0.
19
"""
20
21
def __init__(self, default_value=0, min=None, max=None, **kwargs):
22
"""
23
Initialize integer trait.
24
25
Parameters:
26
- default_value: int - Default integer value
27
- min: int|None - Minimum allowed value
28
- max: int|None - Maximum allowed value
29
- **kwargs: Additional TraitType parameters
30
"""
31
32
class CInt(Int):
33
"""
34
Casting version of Int that attempts to convert values to integers.
35
36
Tries to cast values to int before validation, allowing for
37
automatic conversion from compatible types.
38
"""
39
40
def __init__(self, default_value=0, min=None, max=None, **kwargs):
41
"""
42
Initialize casting integer trait.
43
44
Parameters:
45
- default_value: int - Default integer value
46
- min: int|None - Minimum allowed value
47
- max: int|None - Maximum allowed value
48
- **kwargs: Additional TraitType parameters
49
"""
50
```
51
52
Python 2 long integer support:
53
54
```python { .api }
55
class Long(TraitType):
56
"""
57
Long integer trait type (Python 2 only).
58
59
Validates long integers with optional bounds.
60
Default value is 0L.
61
"""
62
63
def __init__(self, default_value=0, min=None, max=None, **kwargs):
64
"""
65
Initialize long integer trait.
66
67
Parameters:
68
- default_value: long - Default long value
69
- min: long|None - Minimum allowed value
70
- max: long|None - Maximum allowed value
71
- **kwargs: Additional TraitType parameters
72
"""
73
74
class CLong(Long):
75
"""
76
Casting version of Long (Python 2 only).
77
"""
78
79
def __init__(self, default_value=0, min=None, max=None, **kwargs):
80
"""
81
Initialize casting long trait.
82
83
Parameters:
84
- default_value: long - Default long value
85
- min: long|None - Minimum allowed value
86
- max: long|None - Maximum allowed value
87
- **kwargs: Additional TraitType parameters
88
"""
89
90
class Integer(TraitType):
91
"""
92
Integer trait that casts longs to ints when possible (Python 2 only).
93
94
Handles both int and long types, converting longs to ints
95
when they fit in int range.
96
"""
97
98
def __init__(self, default_value=0, **kwargs):
99
"""
100
Initialize integer trait.
101
102
Parameters:
103
- default_value: int|long - Default value
104
- **kwargs: Additional TraitType parameters
105
"""
106
```
107
108
#### Float Types
109
110
Floating-point trait types with optional bounds validation.
111
112
```python { .api }
113
class Float(TraitType):
114
"""
115
Float trait type with optional min/max bounds.
116
117
Validates that values are floats within specified range.
118
Default value is 0.0.
119
"""
120
121
def __init__(self, default_value=0.0, min=None, max=None, **kwargs):
122
"""
123
Initialize float trait.
124
125
Parameters:
126
- default_value: float - Default float value
127
- min: float|None - Minimum allowed value
128
- max: float|None - Maximum allowed value
129
- **kwargs: Additional TraitType parameters
130
"""
131
132
class CFloat(Float):
133
"""
134
Casting version of Float that attempts to convert values to floats.
135
136
Tries to cast values to float before validation.
137
"""
138
139
def __init__(self, default_value=0.0, min=None, max=None, **kwargs):
140
"""
141
Initialize casting float trait.
142
143
Parameters:
144
- default_value: float - Default float value
145
- min: float|None - Minimum allowed value
146
- max: float|None - Maximum allowed value
147
- **kwargs: Additional TraitType parameters
148
"""
149
```
150
151
#### Complex Number Types
152
153
Complex number trait types for mathematical computations.
154
155
```python { .api }
156
class Complex(TraitType):
157
"""
158
Complex number trait type.
159
160
Validates complex number values.
161
Default value is 0.0+0.0j.
162
"""
163
164
def __init__(self, default_value=0.0+0.0j, **kwargs):
165
"""
166
Initialize complex trait.
167
168
Parameters:
169
- default_value: complex - Default complex value
170
- **kwargs: Additional TraitType parameters
171
"""
172
173
class CComplex(Complex):
174
"""
175
Casting version of Complex that attempts to convert values to complex.
176
177
Tries to cast values to complex before validation.
178
"""
179
180
def __init__(self, default_value=0.0+0.0j, **kwargs):
181
"""
182
Initialize casting complex trait.
183
184
Parameters:
185
- default_value: complex - Default complex value
186
- **kwargs: Additional TraitType parameters
187
"""
188
```
189
190
### String Types
191
192
String trait types for text data with encoding handling.
193
194
```python { .api }
195
class Bytes(TraitType):
196
"""
197
Byte string trait type.
198
199
Validates byte string (str in Python 2, bytes in Python 3).
200
Default value is b''.
201
"""
202
203
def __init__(self, default_value=b'', **kwargs):
204
"""
205
Initialize bytes trait.
206
207
Parameters:
208
- default_value: bytes - Default bytes value
209
- **kwargs: Additional TraitType parameters
210
"""
211
212
class CBytes(Bytes):
213
"""
214
Casting version of Bytes that attempts to convert values to bytes.
215
216
Tries to encode strings to bytes using utf-8.
217
"""
218
219
def __init__(self, default_value=b'', **kwargs):
220
"""
221
Initialize casting bytes trait.
222
223
Parameters:
224
- default_value: bytes - Default bytes value
225
- **kwargs: Additional TraitType parameters
226
"""
227
228
class Unicode(TraitType):
229
"""
230
Unicode string trait type.
231
232
Validates unicode strings (unicode in Python 2, str in Python 3).
233
Default value is u''.
234
"""
235
236
def __init__(self, default_value=u'', **kwargs):
237
"""
238
Initialize unicode trait.
239
240
Parameters:
241
- default_value: unicode|str - Default unicode value
242
- **kwargs: Additional TraitType parameters
243
"""
244
245
class CUnicode(Unicode):
246
"""
247
Casting version of Unicode that attempts to convert values to unicode.
248
249
Tries to decode bytes to unicode using utf-8.
250
"""
251
252
def __init__(self, default_value=u'', **kwargs):
253
"""
254
Initialize casting unicode trait.
255
256
Parameters:
257
- default_value: unicode|str - Default unicode value
258
- **kwargs: Additional TraitType parameters
259
"""
260
```
261
262
### String Validation Types
263
264
Specialized string types with validation rules.
265
266
```python { .api }
267
class ObjectName(TraitType):
268
"""
269
String trait holding a valid Python object name.
270
271
Validates that the string is a valid Python identifier.
272
"""
273
274
def __init__(self, default_value=u'', **kwargs):
275
"""
276
Initialize object name trait.
277
278
Parameters:
279
- default_value: str - Default identifier name
280
- **kwargs: Additional TraitType parameters
281
"""
282
283
class DottedObjectName(TraitType):
284
"""
285
String trait holding a valid dotted object name.
286
287
Validates dotted names like "A.b3._c" where each component
288
is a valid Python identifier.
289
"""
290
291
def __init__(self, default_value=u'', **kwargs):
292
"""
293
Initialize dotted object name trait.
294
295
Parameters:
296
- default_value: str - Default dotted name
297
- **kwargs: Additional TraitType parameters
298
"""
299
```
300
301
### Boolean Types
302
303
Boolean trait types for true/false values.
304
305
```python { .api }
306
class Bool(TraitType):
307
"""
308
Boolean trait type.
309
310
Validates boolean values (True/False).
311
Default value is False.
312
"""
313
314
def __init__(self, default_value=False, **kwargs):
315
"""
316
Initialize boolean trait.
317
318
Parameters:
319
- default_value: bool - Default boolean value
320
- **kwargs: Additional TraitType parameters
321
"""
322
323
class CBool(Bool):
324
"""
325
Casting version of Bool that attempts to convert values to boolean.
326
327
Casts values to bool using Python's truth testing.
328
"""
329
330
def __init__(self, default_value=False, **kwargs):
331
"""
332
Initialize casting boolean trait.
333
334
Parameters:
335
- default_value: bool - Default boolean value
336
- **kwargs: Additional TraitType parameters
337
"""
338
```
339
340
### Universal Type
341
342
Type that accepts any value without validation.
343
344
```python { .api }
345
class Any(TraitType):
346
"""
347
Trait type that allows any value.
348
349
No validation is performed - accepts any Python value.
350
Default value is None.
351
"""
352
353
def __init__(self, default_value=None, **kwargs):
354
"""
355
Initialize any-type trait.
356
357
Parameters:
358
- default_value: any - Default value (typically None)
359
- **kwargs: Additional TraitType parameters
360
"""
361
```
362
363
## Usage Examples
364
365
### Numeric Constraints
366
367
```python
368
from traitlets import HasTraits, Int, Float
369
370
class Rectangle(HasTraits):
371
width = Int(min=1, max=1000) # Width between 1-1000
372
height = Int(min=1, max=1000) # Height between 1-1000
373
area = Float(min=0.0) # Non-negative area
374
375
rect = Rectangle(width=10, height=20)
376
rect.area = rect.width * rect.height # 200.0
377
# rect.width = 0 # Would raise TraitError (below minimum)
378
# rect.height = 1500 # Would raise TraitError (above maximum)
379
```
380
381
### String Validation
382
383
```python
384
from traitlets import HasTraits, Unicode, ObjectName, DottedObjectName
385
386
class ClassDefinition(HasTraits):
387
name = ObjectName() # Valid Python identifier
388
module = DottedObjectName() # Valid dotted module name
389
docstring = Unicode() # Any unicode string
390
391
cls_def = ClassDefinition(
392
name="MyClass",
393
module="my.package.module",
394
docstring="A sample class"
395
)
396
397
# cls_def.name = "123invalid" # Would raise TraitError (invalid identifier)
398
# cls_def.module = "my..invalid" # Would raise TraitError (invalid dotted name)
399
```
400
401
### Type Casting
402
403
```python
404
from traitlets import HasTraits, CInt, CFloat, CBool
405
406
class FlexibleTypes(HasTraits):
407
count = CInt() # Casts to int
408
ratio = CFloat() # Casts to float
409
enabled = CBool() # Casts to bool
410
411
obj = FlexibleTypes()
412
obj.count = "42" # Automatically converts to 42
413
obj.ratio = "3.14" # Automatically converts to 3.14
414
obj.enabled = "yes" # Automatically converts to True
415
```
416
417
### Default Values
418
419
```python
420
from traitlets import HasTraits, Unicode, Int, Bool
421
422
class Configuration(HasTraits):
423
host = Unicode(u"localhost") # Default host
424
port = Int(8080) # Default port
425
debug = Bool(False) # Default debug off
426
name = Unicode() # Default empty string u''
427
428
config = Configuration()
429
print(config.host) # "localhost"
430
print(config.port) # 8080
431
print(config.debug) # False
432
print(config.name) # u''
433
```