A pure Python library providing typed attributes with validation, change notifications, and configuration management for the IPython/Jupyter ecosystem.
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.
Foundation class for all container trait types.
class Container(Instance):
"""
Base class for container trait types.
Provides common functionality for collections including element
type validation and change notification setup.
"""
def __init__(self, trait=None, default_value=Undefined, **kwargs):
"""
Initialize container trait.
Parameters:
- trait: TraitType|None - Element type validator
- default_value: any - Default container value
- **kwargs: Additional TraitType parameters
"""List trait types with element validation and size constraints.
class List(Container):
"""
Python list trait type with element validation.
Validates list values with optional element type checking
and size constraints. Default value is empty list [].
"""
def __init__(self, trait=None, default_value=Undefined, minlen=0, maxlen=sys.maxsize, **kwargs):
"""
Initialize list trait.
Parameters:
- trait: TraitType|None - Element type for validation
- default_value: list - Default list value ([] if Undefined, None if not specified)
- minlen: int - Minimum list length
- maxlen: int - Maximum list length
- **kwargs: Additional TraitType parameters
"""Set trait types for unordered collections of unique elements.
class Set(List):
"""
Python set trait type with element validation.
Validates set values with optional element type checking
and size constraints. Default value is empty set set().
"""
def __init__(self, trait=None, default_value=Undefined, minlen=0, maxlen=sys.maxsize, **kwargs):
"""
Initialize set trait.
Parameters:
- trait: TraitType|None - Element type for validation
- default_value: set - Default set value (set() if Undefined, None if not specified)
- minlen: int - Minimum set length
- maxlen: int - Maximum set length
- **kwargs: Additional TraitType parameters
"""Tuple trait types for immutable sequences with fixed or variable element types.
class Tuple(TraitType):
"""
Python tuple trait type with element validation.
Supports both fixed-length tuples with per-element type
validation and variable-length tuples with homogeneous elements.
"""
def __init__(self, *traits, **kwargs):
"""
Initialize tuple trait.
Can be used in two modes:
1. Fixed-length: Tuple(Int(), Unicode(), Bool()) - exactly 3 elements
2. Variable-length: Tuple(default_value=()) - any length tuple
Parameters:
- *traits: TraitType instances for fixed-length validation
- default_value: tuple - Default tuple value (overrides traits mode)
- **kwargs: Additional TraitType parameters
"""Dictionary trait types with key and value validation.
class Dict(TraitType):
"""
Python dict trait type with key/value validation.
Supports validation of dictionary values with optional per-key
type specification or uniform value type validation.
"""
def __init__(self, trait=None, traits=None, default_value=Undefined, **kwargs):
"""
Initialize dict trait.
Can be used in three modes:
1. Uniform values: Dict(Unicode()) - all values must be unicode
2. Per-key types: Dict(traits={'name': Unicode(), 'age': Int()})
3. Unvalidated: Dict() - any dict structure allowed
Parameters:
- trait: TraitType|None - Uniform value type validator
- traits: dict|None - Per-key type validators {key: TraitType}
- default_value: dict - Default dict value ({} if Undefined)
- **kwargs: Additional TraitType parameters
"""from traitlets import HasTraits, List, Unicode, Int
class TodoList(HasTraits):
items = List(Unicode()) # List of strings
priorities = List(Int(min=1, max=5)) # List of priority numbers 1-5
tags = List(minlen=1) # List with at least 1 element
todo = TodoList()
todo.items = ["Buy milk", "Walk dog", "Write code"]
todo.priorities = [2, 1, 3]
todo.tags = ["urgent"]
# todo.items = [123, 456] # Would raise TraitError (not strings)
# todo.priorities = [0, 6] # Would raise TraitError (out of range)
# todo.tags = [] # Would raise TraitError (too short)from traitlets import HasTraits, Dict, Unicode, Int, Bool
class UserProfile(HasTraits):
metadata = Dict(Unicode()) # Dict with string values
settings = Dict(traits={ # Dict with specific key types
'theme': Unicode(),
'notifications': Bool(),
'max_items': Int(min=1)
})
data = Dict() # Any dict structure
user = UserProfile()
user.metadata = {'role': 'admin', 'department': 'engineering'}
user.settings = {
'theme': 'dark',
'notifications': True,
'max_items': 50
}
user.data = {'scores': [1, 2, 3], 'nested': {'key': 'value'}}
# user.metadata = {'count': 123} # Would raise TraitError (value not string)
# user.settings = {'theme': 123} # Would raise TraitError (theme not string)from traitlets import HasTraits, Tuple, Unicode, Int, Float
class Coordinate(HasTraits):
point_2d = Tuple(Float(), Float()) # (x, y) coordinates
point_3d = Tuple(Float(), Float(), Float()) # (x, y, z) coordinates
labeled_point = Tuple(Unicode(), Float(), Float()) # (label, x, y)
coord = Coordinate()
coord.point_2d = (1.5, 2.7)
coord.point_3d = (1.0, 2.0, 3.0)
coord.labeled_point = ("center", 0.0, 0.0)
# coord.point_2d = (1.0, 2.0, 3.0) # Would raise TraitError (wrong length)
# coord.point_3d = ("x", "y", "z") # Would raise TraitError (not floats)from traitlets import HasTraits, Set, Unicode
class TaggedItem(HasTraits):
tags = Set(Unicode(), minlen=1, maxlen=10) # 1-10 unique string tags
item = TaggedItem()
item.tags = {"python", "programming", "tutorial"}
# Automatically removes duplicates
item.tags = {"python", "python", "code"} # Becomes {"python", "code"}
# item.tags = set() # Would raise TraitError (too short)
# item.tags = {1, 2, 3} # Would raise TraitError (not strings)from traitlets import HasTraits, TCPAddress
class Server(HasTraits):
bind_address = TCPAddress()
proxy_address = TCPAddress(('192.168.1.100', 8080))
server = Server()
server.bind_address = ('0.0.0.0', 3000)
print(server.proxy_address) # ('192.168.1.100', 8080)
# server.bind_address = ('localhost', '3000') # Would raise TraitError (port not int)
# server.bind_address = ('host', 80, 'extra') # Would raise TraitError (wrong length)import re
from traitlets import HasTraits, CRegExp
class Validator(HasTraits):
email_pattern = CRegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
phone_pattern = CRegExp()
validator = Validator()
# Can set as string pattern
validator.phone_pattern = r'^\d{3}-\d{3}-\d{4}$'
# Or as compiled regex
validator.phone_pattern = re.compile(r'^\(\d{3}\) \d{3}-\d{4}$')
# Access compiled pattern
if validator.email_pattern.match('user@example.com'):
print("Valid email")from traitlets import HasTraits, Tuple
class FlexibleData(HasTraits):
coordinates = Tuple() # Any length tuple
rgb_color = Tuple(default_value=(255, 255, 255)) # Default white
data = FlexibleData()
data.coordinates = (1, 2) # 2D point
data.coordinates = (1, 2, 3) # 3D point
data.coordinates = (1, 2, 3, 4) # 4D point
print(data.rgb_color) # (255, 255, 255)Install with Tessl CLI
npx tessl i tessl/pypi-traitlets