or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-types.mdbasic-types.mdconfiguration.mdcontainer-types.mdcore-traits.mdindex.mdlinking.mdobservers.md
tile.json

tessl/pypi-traitlets

A pure Python library providing typed attributes with validation, change notifications, and configuration management for the IPython/Jupyter ecosystem.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/traitlets@4.3.x

To install, run

npx @tessl/cli install tessl/pypi-traitlets@4.3.0

index.mddocs/

Traitlets

A 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.

Package Information

  • Package Name: traitlets
  • Language: Python
  • Installation: pip install traitlets
  • Dependencies: ipython_genutils, six, decorator

Core Imports

import traitlets

Common imports for trait types and classes:

from traitlets import HasTraits, TraitType, Unicode, Int, Float, Bool, List, Dict

For configuration:

from traitlets.config import Application, Configurable

Basic Usage

from 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())

Architecture

Traitlets implements a descriptor-based trait system with several key components:

  • HasTraits: Base class providing trait functionality and change notifications
  • TraitType: Base descriptor class for all trait types with validation and metadata
  • Trait Types: Specific validators for different data types (Int, Unicode, Bool, etc.)
  • Observers: Decorators and handlers for responding to trait changes
  • Configuration System: Application framework with file-based configuration support
  • Linking: Mechanisms to synchronize traits between different objects

This design enables type-safe attribute management with automatic validation, change notifications, and sophisticated configuration capabilities that scale from simple classes to complex applications.

Capabilities

Core Trait System

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): ...

Core Trait System

Basic Trait Types

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): ...

Basic Trait Types

Container Trait Types

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): ...

Container Trait Types

Advanced Trait Types

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): ...

Advanced Trait Types

Observers and Decorators

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"""

Observers and Decorators

Trait Linking

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_link

Trait Linking

Configuration System

Application 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): ...

Configuration System

Types

Core Types

# 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 Objects

# 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"""