A pure Python library providing typed attributes with validation, change notifications, and configuration management for the IPython/Jupyter ecosystem.
The foundational trait system providing HasTraits base class, TraitType descriptors, and change notification mechanisms. This forms the core of traitlets' typed attribute functionality with validation, metadata, and observer patterns.
The main base class that provides trait functionality to objects. Any class inheriting from HasTraits can use trait descriptors and benefit from change notifications, validation, and metadata features.
class HasTraits:
"""
Base class for objects with traits.
Provides trait functionality including initialization, observation,
and metadata access for trait attributes.
"""
def __init__(self, **kwargs):
"""
Initialize with trait values from kwargs.
Parameters:
- **kwargs: Trait name-value pairs for initialization
"""
def observe(self, handler, names=All, type='change'):
"""
Setup dynamic trait change handler.
Parameters:
- handler: callable(change) - Function to call on trait changes
- names: str|list - Trait names to observe or All for all traits
- type: str - Type of change to observe ('change', etc.)
"""
def unobserve(self, handler, names=All, type='change'):
"""
Remove trait change handler.
Parameters:
- handler: callable - Handler function to remove
- names: str|list - Trait names or All
- type: str - Type of change handler
"""
def unobserve_all(self, name=All):
"""
Remove all handlers for given trait name.
Parameters:
- name: str - Trait name or All for all traits
"""
def on_trait_change(self, handler, name=None, remove=False):
"""
Deprecated observer method.
Parameters:
- handler: callable - Handler function
- name: str - Trait name
- remove: bool - Whether to remove handler
"""
def add_traits(self, **traits):
"""
Dynamically add trait attributes to instance.
Parameters:
- **traits: TraitType instances to add as attributes
"""
def set_trait(self, name, value):
"""
Forcibly set trait value, bypassing read-only restrictions.
Parameters:
- name: str - Trait name
- value: any - Value to set
"""
def has_trait(self, name):
"""
Check if object has trait with given name.
Parameters:
- name: str - Trait name
Returns:
bool - True if trait exists
"""
def traits(self, **metadata):
"""
Get dict of all traits matching metadata filter.
Parameters:
- **metadata: Metadata key-value pairs to filter by
Returns:
dict - {trait_name: TraitType} mapping
"""
def trait_names(self, **metadata):
"""
Get list of trait names matching metadata filter.
Parameters:
- **metadata: Metadata key-value pairs to filter by
Returns:
list - List of trait names
"""
def trait_metadata(self, traitname, key, default=None):
"""
Get metadata value for specific trait.
Parameters:
- traitname: str - Name of trait
- key: str - Metadata key
- default: any - Default value if key not found
Returns:
any - Metadata value
"""
def hold_trait_notifications(self):
"""
Context manager to bundle trait notifications.
Returns:
context manager - Bundles notifications until exit
"""
@classmethod
def class_traits(cls, **metadata):
"""
Get dict of class traits matching metadata filter.
Parameters:
- **metadata: Metadata key-value pairs to filter by
Returns:
dict - {trait_name: TraitType} mapping
"""
@classmethod
def class_trait_names(cls, **metadata):
"""
Get list of class trait names matching metadata filter.
Parameters:
- **metadata: Metadata key-value pairs to filter by
Returns:
list - List of trait names
"""
@classmethod
def class_own_traits(cls, **metadata):
"""
Get traits defined on this class only (not inherited).
Parameters:
- **metadata: Metadata key-value pairs to filter by
Returns:
dict - {trait_name: TraitType} mapping
"""
@classmethod
def trait_events(cls, name=None):
"""
Get event handlers for trait.
Parameters:
- name: str - Trait name or None for all
Returns:
dict - Event handler mapping
"""The base class for all trait types, providing validation, metadata, and descriptor functionality. All specific trait types inherit from TraitType.
class TraitType:
"""
Base class for all trait types.
Provides validation, metadata, defaults, and descriptor protocol
implementation for typed attributes.
"""
def __init__(self, default_value=Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs):
"""
Initialize trait type.
Parameters:
- default_value: any - Default value or Undefined
- allow_none: bool - Whether None is allowed as value
- read_only: bool - Whether trait is read-only after set
- help: str - Help text description
- config: bool - Whether trait is configurable
- **kwargs: Additional metadata
"""
def tag(self, **metadata):
"""
Set metadata and return self for chaining.
Parameters:
- **metadata: Metadata key-value pairs
Returns:
TraitType - Self for method chaining
"""
def validate(self, obj, value):
"""
Validate a value for this trait type.
Override in subclasses for specific validation.
Parameters:
- obj: HasTraits - Object containing the trait
- value: any - Value to validate
Returns:
any - Validated/coerced value
Raises:
TraitError - If validation fails
"""
def error(self, obj, value):
"""
Raise TraitError with appropriate message.
Parameters:
- obj: HasTraits - Object containing the trait
- value: any - Invalid value
Raises:
TraitError - Always raised with descriptive message
"""
def info(self):
"""
Return description string for this trait type.
Returns:
str - Human-readable description
"""
def get_metadata(self, key, default=None):
"""
Get metadata value (deprecated, use .metadata dict).
Parameters:
- key: str - Metadata key
- default: any - Default if key not found
Returns:
any - Metadata value
"""
def set_metadata(self, key, value):
"""
Set metadata value (deprecated, use .metadata dict).
Parameters:
- key: str - Metadata key
- value: any - Metadata value
"""
def default_value_repr(self):
"""
Return representation of default value.
Returns:
str - String representation of default
"""Foundation descriptor classes that TraitType builds upon.
class BaseDescriptor:
"""
Base class for all descriptors in traitlets.
Provides the foundation for trait descriptors with
class and instance initialization hooks.
"""
def class_init(self, cls, name):
"""
Part of initialization depending on HasDescriptors class.
Parameters:
- cls: type - Class that declared the trait
- name: str - Name of the attribute
"""
def instance_init(self, obj):
"""
Part of initialization depending on HasDescriptors instance.
Parameters:
- obj: HasDescriptors - Instance being initialized
"""
class HasDescriptors:
"""
Base class for all classes that have descriptors.
Provides setup_instance method for descriptor initialization.
"""
def setup_instance(self, *args, **kwargs):
"""
Called before __init__ to setup descriptors.
Parameters:
- *args: Positional arguments
- **kwargs: Keyword arguments
"""Metaclasses that enable the trait system's functionality.
class MetaHasDescriptors(type):
"""
Metaclass for HasDescriptors that instantiates TraitType class attributes.
Automatically calls class_init on TraitType descriptors and
manages descriptor setup at class creation time.
"""
class MetaHasTraits(MetaHasDescriptors):
"""
Metaclass for HasTraits, extends MetaHasDescriptors.
Provides additional trait-specific metaclass functionality.
"""from traitlets import HasTraits, Unicode, Int
class Person(HasTraits):
name = Unicode()
age = Int(min=0)
person = Person(name="Alice", age=30)
print(person.name) # "Alice"
print(person.age) # 30
# Access trait metadata
traits = person.traits()
trait_names = person.trait_names()from traitlets import TraitType, TraitError
class PositiveInt(TraitType):
info_text = 'a positive integer'
def validate(self, obj, value):
if isinstance(value, int) and value > 0:
return value
self.error(obj, value)
class MyClass(HasTraits):
count = PositiveInt()
obj = MyClass(count=5) # Valid
# obj.count = -1 # Would raise TraitErrorclass Example(HasTraits):
value = Int(help="An important value").tag(category="core", units="meters")
example = Example()
metadata = example.trait_metadata('value', 'category') # "core"
help_text = example.trait_metadata('value', 'help') # "An important value"Install with Tessl CLI
npx tessl i tessl/pypi-traitlets