CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-traitlets

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

Overview
Eval results
Files

advanced-types.mddocs/

Advanced Trait Types

Specialized trait types including class-based types, enums, unions, and network addresses for complex validation scenarios. These provide sophisticated type checking and validation beyond basic Python types.

Capabilities

Class-Based Types

Trait types that validate against specific classes or instances.

Base Class for Class-Based Types

class ClassBasedTraitType(TraitType):
    """
    Base class for Type, Instance, This with string resolution.
    
    Provides common functionality for trait types that reference
    classes, including delayed string-based class resolution.
    """
    
    def __init__(self, klass=None, **kwargs):
        """
        Initialize class-based trait.
        
        Parameters:
        - klass: type|str|None - Class reference or string name
        - **kwargs: Additional TraitType parameters
        """

Class Type Validation

class Type(ClassBasedTraitType):
    """
    Trait whose value must be a subclass of the specified class.
    
    Validates that assigned values are classes (types) that inherit
    from the specified base class.
    """
    
    def __init__(self, klass=None, **kwargs):
        """
        Initialize type trait.
        
        Parameters:
        - klass: type|str|None - Base class or string name
        - **kwargs: Additional TraitType parameters
        """

class ForwardDeclaredType(Type):
    """
    Forward-declared version of Type for classes not yet defined.
    
    Allows referencing classes by string name that will be
    resolved later when the class becomes available.
    """
    
    def __init__(self, klass=None, **kwargs):
        """
        Initialize forward-declared type trait.
        
        Parameters:
        - klass: str - String name of class
        - **kwargs: Additional TraitType parameters
        """

Instance Type Validation

class Instance(ClassBasedTraitType):
    """
    Trait whose value must be an instance of the specified class.
    
    Validates that assigned values are instances of the specified
    class, with optional automatic instance creation.
    """
    
    def __init__(self, klass=None, args=None, kw=None, **kwargs):
        """
        Initialize instance trait.
        
        Parameters:
        - klass: type|str|None - Class or string name
        - args: tuple|None - Arguments for automatic instance creation
        - kw: dict|None - Keyword arguments for automatic instance creation
        - **kwargs: Additional TraitType parameters
        """

class ForwardDeclaredInstance(Instance):
    """
    Forward-declared version of Instance for classes not yet defined.
    
    Allows referencing classes by string name that will be
    resolved later when the class becomes available.
    """
    
    def __init__(self, klass=None, args=None, kw=None, **kwargs):
        """
        Initialize forward-declared instance trait.
        
        Parameters:
        - klass: str - String name of class
        - args: tuple|None - Arguments for instance creation
        - kw: dict|None - Keyword arguments for instance creation
        - **kwargs: Additional TraitType parameters
        """

Self-Reference Type

class This(ClassBasedTraitType):
    """
    Trait for instances of the same class as the trait owner.
    
    Automatically resolves to validate instances of the class
    that declares this trait.
    """
    
    def __init__(self, **kwargs):
        """
        Initialize self-reference trait.
        
        Parameters:
        - **kwargs: Additional TraitType parameters
        """

Union Types

Trait type representing multiple allowed types.

class Union(TraitType):
    """
    Union type representing multiple allowed trait types.
    
    Accepts values that validate against any of the specified
    trait types, trying each in order until one succeeds.
    """
    
    def __init__(self, trait_types, **kwargs):
        """
        Initialize union trait.
        
        Parameters:
        - trait_types: list - Sequence of TraitType instances
        - **kwargs: Additional TraitType parameters
        """

Enumeration Types

Trait types for restricting values to specific choices.

Value-Based Enums

class Enum(TraitType):
    """
    Enum trait with value from a given sequence.
    
    Restricts values to those in the specified values sequence,
    performing exact equality matching.
    """
    
    def __init__(self, values, **kwargs):
        """
        Initialize enum trait.
        
        Parameters:
        - values: sequence - Allowed values (list, tuple, set, etc.)
        - **kwargs: Additional TraitType parameters
        """

class CaselessStrEnum(Enum):
    """
    Case-insensitive string enum.
    
    Like Enum but performs case-insensitive matching for string values.
    """
    
    def __init__(self, values, **kwargs):
        """
        Initialize case-insensitive string enum trait.
        
        Parameters:
        - values: sequence - Allowed string values
        - **kwargs: Additional TraitType parameters
        """

Python Enum Integration

class UseEnum(TraitType):
    """
    Trait using a Python Enum class as the model.
    
    Integrates with Python's enum module, accepting enum members
    as values and providing enum-specific validation.
    """
    
    def __init__(self, enum_class, **kwargs):
        """
        Initialize enum-based trait.
        
        Parameters:
        - enum_class: Enum - Python Enum class to use
        - **kwargs: Additional TraitType parameters
        """

Network Address Types

Specialized trait types for network addresses.

class TCPAddress(TraitType):
    """
    Trait for (ip, port) tuple representing TCP addresses.
    
    Validates 2-tuple with string IP address and integer port.
    Default value is ('127.0.0.1', 0).
    """
    
    def __init__(self, default_value=('127.0.0.1', 0), **kwargs):
        """
        Initialize TCP address trait.
        
        Parameters:
        - default_value: tuple - Default (ip, port) tuple
        - **kwargs: Additional TraitType parameters
        """

Regular Expression Types

Specialized trait types for compiled regular expressions.

class CRegExp(TraitType):
    """
    Compiled regular expression trait type.
    
    Accepts regex pattern strings or compiled regex objects,
    storing as compiled re.Pattern objects.
    """
    
    def __init__(self, default_value=None, **kwargs):
        """
        Initialize regex trait.
        
        Parameters:
        - default_value: str|Pattern|None - Default regex pattern
        - **kwargs: Additional TraitType parameters
        """

Usage Examples

Class Type Validation

from traitlets import HasTraits, Type, Instance

class Animal:
    pass

class Dog(Animal):
    def bark(self):
        return "Woof!"

class Cat(Animal):
    def meow(self):
        return "Meow!"

class Pet(HasTraits):
    animal_type = Type(klass=Animal)      # Must be Animal subclass
    pet = Instance(klass=Animal)          # Must be Animal instance

# Using the trait
pet_config = Pet()
pet_config.animal_type = Dog              # Valid - Dog is subclass of Animal
pet_config.pet = Dog()                    # Valid - Dog() is instance of Animal

# pet_config.animal_type = Dog()          # Would raise TraitError (instance, not class)
# pet_config.pet = Dog                    # Would raise TraitError (class, not instance)

Forward Declaration

from traitlets import HasTraits, ForwardDeclaredInstance

class TreeNode(HasTraits):
    # Can reference TreeNode before it's fully defined
    parent = ForwardDeclaredInstance('TreeNode', allow_none=True)
    children = List(ForwardDeclaredInstance('TreeNode'))

root = TreeNode()
child = TreeNode(parent=root)
root.children = [child]

Self-Reference with This

from traitlets import HasTraits, This, List

class LinkedListNode(HasTraits):
    value = Int()
    next_node = This(allow_none=True)     # References same class
    
class Tree(HasTraits):
    children = List(This())               # List of Tree instances

# Usage
node1 = LinkedListNode(value=1)
node2 = LinkedListNode(value=2, next_node=node1)

tree = Tree()
subtree1 = Tree()
subtree2 = Tree()
tree.children = [subtree1, subtree2]

Union Types

from traitlets import HasTraits, Union, Unicode, Int, Float

class FlexibleData(HasTraits):
    # Can be string, integer, or float
    value = Union([Unicode(), Int(), Float()])
    
    # Can be number or special string values
    size = Union([Int(min=0), Enum(['auto', 'fill', 'content'])])

data = FlexibleData()
data.value = "hello"      # String - valid
data.value = 42           # Integer - valid  
data.value = 3.14         # Float - valid

data.size = 100           # Integer - valid
data.size = "auto"        # Enum string - valid
# data.size = "invalid"   # Would raise TraitError (not in union)

Enumeration Values

from traitlets import HasTraits, Enum, CaselessStrEnum
from enum import Enum as PyEnum

class Priority(PyEnum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

class Task(HasTraits):
    status = Enum(['pending', 'active', 'complete'])
    theme = CaselessStrEnum(['Light', 'Dark', 'Auto'])
    priority = UseEnum(Priority)

task = Task()
task.status = 'pending'          # Exact match required
task.theme = 'light'             # Case-insensitive - becomes 'Light'
task.theme = 'DARK'              # Case-insensitive - becomes 'Dark'
task.priority = Priority.HIGH    # Enum member

# task.status = 'PENDING'        # Would raise TraitError (case sensitive)
# task.priority = 3              # Would raise TraitError (not enum member)

Instance with Auto-Creation

from traitlets import HasTraits, Instance, Unicode

class DatabaseConfig:
    def __init__(self, host='localhost', port=5432):
        self.host = host
        self.port = port

class Application(HasTraits):
    # Automatically creates DatabaseConfig() if none provided
    db_config = Instance(DatabaseConfig, args=(), kw={'host': 'db.example.com'})
    
    # Manual instance required
    logger = Instance('logging.Logger')  # String class name

app = Application()
print(app.db_config.host)    # 'db.example.com' (auto-created)
print(app.db_config.port)    # 5432 (auto-created)

import logging
app.logger = logging.getLogger('app')  # Must set manually

Complex Union Example

from traitlets import HasTraits, Union, Instance, Unicode, Int, List

class ConfigValue(HasTraits):
    # Can be single value or list of values
    # Each value can be string, int, or a nested ConfigValue
    value = Union([
        Unicode(),                           # Simple string
        Int(),                              # Simple integer  
        Instance('ConfigValue'),            # Nested config
        List(Unicode()),                    # List of strings
        List(Int()),                        # List of integers
        List(Instance('ConfigValue'))       # List of nested configs
    ])

# Various valid assignments
config = ConfigValue()
config.value = "simple string"                    # String
config.value = 42                                 # Integer
config.value = ["list", "of", "strings"]         # String list
config.value = [1, 2, 3]                         # Integer list

# Nested configuration
nested = ConfigValue()
nested.value = "nested value"
config.value = nested                             # Single nested

config.value = [ConfigValue(), ConfigValue()]     # List of nested

Install with Tessl CLI

npx tessl i tessl/pypi-traitlets

docs

advanced-types.md

basic-types.md

configuration.md

container-types.md

core-traits.md

index.md

linking.md

observers.md

tile.json