A pure Python library providing typed attributes with validation, change notifications, and configuration management for the IPython/Jupyter ecosystem.
npx @tessl/cli install tessl/pypi-traitlets@4.3.0A pure Python library providing a lightweight trait system for typed attributes with validation, change notifications, and configuration management. Traitlets serves as the foundational configuration system for the IPython and Jupyter ecosystems, enabling robust attribute management with automatic validation, coercion, and change tracking.
pip install traitletsipython_genutils, six, decoratorimport traitletsCommon imports for trait types and classes:
from traitlets import HasTraits, TraitType, Unicode, Int, Float, Bool, List, DictFor configuration:
from traitlets.config import Application, Configurablefrom traitlets import HasTraits, Unicode, Int, Float, observe
class Person(HasTraits):
name = Unicode()
age = Int(min=0, max=150)
height = Float(min=0.0)
@observe('name')
def _name_changed(self, change):
print(f"Name changed from {change['old']} to {change['new']}")
# Create and use the class
person = Person(name="Alice", age=30, height=5.6)
person.name = "Bob" # Triggers observer
person.age = 25 # Validates range
# Access trait metadata
print(person.traits())
print(person.trait_names())Traitlets implements a descriptor-based trait system with several key components:
This design enables type-safe attribute management with automatic validation, change notifications, and sophisticated configuration capabilities that scale from simple classes to complex applications.
The foundational trait system providing HasTraits base class, TraitType descriptors, and change notification mechanisms. This forms the core of traitlets' typed attribute functionality.
class HasTraits:
def __init__(self, **kwargs): ...
def observe(self, handler, names=All, type='change'): ...
def traits(self, **metadata): ...
class TraitType:
def __init__(self, default_value=Undefined, allow_none=False, **kwargs): ...
def tag(self, **metadata): ...
def validate(self, obj, value): ...Fundamental trait types for common Python data types including integers, floats, strings, booleans, and complex numbers, with optional validation parameters.
class Int(TraitType):
def __init__(self, default_value=0, min=None, max=None, **kwargs): ...
class Unicode(TraitType):
def __init__(self, default_value=u'', **kwargs): ...
class Float(TraitType):
def __init__(self, default_value=0.0, min=None, max=None, **kwargs): ...
class Bool(TraitType):
def __init__(self, default_value=False, **kwargs): ...Container trait types for Python collections including lists, dictionaries, sets, and tuples, with element type validation and size constraints.
class List(Container):
def __init__(self, trait=None, default_value=Undefined, minlen=0, maxlen=sys.maxsize, **kwargs): ...
class Dict(TraitType):
def __init__(self, trait=None, traits=None, default_value=Undefined, **kwargs): ...
class Set(Container):
def __init__(self, trait=None, default_value=Undefined, minlen=0, maxlen=sys.maxsize, **kwargs): ...
class Tuple(TraitType):
def __init__(self, *traits, **kwargs): ...Specialized trait types including class-based types, enums, unions, and network addresses for complex validation scenarios.
class Instance(TraitType):
def __init__(self, klass=None, args=None, kw=None, **kwargs): ...
class Type(TraitType):
def __init__(self, klass=None, **kwargs): ...
class Union(TraitType):
def __init__(self, trait_types, **kwargs): ...
class Enum(TraitType):
def __init__(self, values, **kwargs): ...Decorators and handlers for observing trait changes, validating values, and providing dynamic defaults.
def observe(*names, type='change'):
"""Decorator to observe trait changes"""
def validate(*names):
"""Decorator to register cross-validator"""
def default(name):
"""Decorator for dynamic default value generator"""Functions for linking traits between objects, enabling synchronization of trait values across different instances.
class link:
def __init__(self, source, target): ...
def unlink(self): ...
class directional_link:
def __init__(self, source, target, transform=None): ...
def unlink(self): ...
# Alias for directional_link
dlink = directional_linkApplication framework and configuration management including configurable base classes, config file loading, and command-line argument processing.
class Application(SingletonConfigurable):
def initialize(self, argv=None): ...
def start(self): ...
def parse_command_line(self, argv=None): ...
class Configurable(HasTraits):
def __init__(self, config=None, parent=None, **kwargs): ...
class Config(dict):
def merge(self, other): ...# Sentinel values
Undefined = Sentinel('Undefined', 'traitlets', 'Used to specify no default value')
All = Sentinel('All', 'traitlets', 'Used to listen to all trait notifications')
# Deprecated alias
NoDefaultSpecified = Undefined # Deprecated: use Undefined instead
# Exception classes
class TraitError(Exception):
"""Exception for trait-related errors"""
# Type checking
def is_trait(t):
"""Returns whether the given value is an instance or subclass of TraitType"""# Event handler classes
class EventHandler:
"""Base class for event handlers"""
class ObserveHandler(EventHandler):
"""Handler for observe decorator"""
class ValidateHandler(EventHandler):
"""Handler for validate decorator"""
class DefaultHandler(EventHandler):
"""Handler for default decorator"""