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

configuration.mddocs/

Configuration System

Application framework and configuration management including configurable base classes, config file loading, and command-line argument processing. This provides a complete system for building configurable applications with the IPython/Jupyter ecosystem.

Capabilities

Application Classes

Base classes for building configurable applications with command-line interface support.

class Application(SingletonConfigurable):
    """
    Singleton application with full configuration support.
    
    Provides a complete application framework with configuration
    file loading, command-line argument parsing, logging setup,
    and plugin management.
    """
    
    # Key attributes
    name = Unicode(u'application')
    description = Unicode(u'')
    version = Unicode(u'0.0')
    classes = List()
    aliases = Dict()
    flags = Dict()
    config = Instance(Config)
    
    def initialize(self, argv=None):
        """
        Basic configuration setup.
        
        Parses command line, loads config files, and initializes
        the application with the resulting configuration.
        
        Parameters:
        - argv: list|None - Command line arguments (sys.argv if None)
        """
    
    def start(self):
        """
        Start the application mainloop.
        
        Override this method in subclasses to implement the main
        application logic. Called after initialization is complete.
        """
    
    def parse_command_line(self, argv=None):
        """
        Parse command line arguments.
        
        Processes command line flags and aliases to update
        configuration. Handles --help and --version automatically.
        
        Parameters:
        - argv: list|None - Arguments to parse (sys.argv if None)
        """
    
    def load_config_file(self, filename, path=None):
        """
        Load configuration from file.
        
        Supports Python config files (.py) and JSON config files (.json).
        Merges loaded configuration with existing config.
        
        Parameters:
        - filename: str - Config file name
        - path: str|list|None - Search paths for config file
        """
    
    def print_help(self, classes=False):
        """
        Print application help message.
        
        Shows usage, description, command line flags, aliases,
        and optionally detailed help for configurable classes.
        
        Parameters:
        - classes: bool - Whether to show help for configurable classes
        """
    
    @classmethod
    def launch_instance(cls, argv=None, **kwargs):
        """
        Class method to launch application instance.
        
        Creates an instance, initializes it, and starts it.
        Commonly used pattern for application entry points.
        
        Parameters:
        - argv: list|None - Command line arguments
        - **kwargs: Additional arguments passed to constructor
        """

class ApplicationError(Exception):
    """Exception raised by Application classes."""

class LevelFormatter(logging.Formatter):
    """
    Logging formatter with highlevel field.
    
    Provides enhanced logging formatting for applications
    with support for different log levels and highlighting.
    """

Configurable Base Classes

Base classes for objects that can be configured through the configuration system.

class Configurable(HasTraits):
    """
    Base class for configurable objects.
    
    Integrates with the configuration system to allow objects
    to be configured through config files and command line arguments.
    """
    
    config = Instance(Config)
    parent = Instance('traitlets.config.configurable.Configurable', allow_none=True)
    
    def __init__(self, config=None, parent=None, **kwargs):
        """
        Initialize configurable object.
        
        Parameters:
        - config: Config|None - Configuration object
        - parent: Configurable|None - Parent configurable object
        - **kwargs: Additional trait values
        """

class ConfigurableError(Exception):
    """Exception raised by Configurable classes."""

class MultipleInstanceError(ConfigurableError):
    """Exception raised when multiple instances are not allowed."""

class LoggingConfigurable(Configurable):
    """
    Configurable base class with logging support.
    
    Adds logging capabilities to configurable objects with
    automatic logger setup and configuration.
    """

class SingletonConfigurable(LoggingConfigurable):
    """
    Singleton version of LoggingConfigurable.
    
    Ensures only one instance exists per class, commonly used
    for application and manager classes.
    """

Configuration Classes

Classes for managing configuration data.

class Config(dict):
    """
    Configuration object for storing config data.
    
    Dictionary-like object with special behavior for configuration
    including merging, collision detection, and nested access.
    """
    
    def merge(self, other):
        """
        Merge with another config object.
        
        Recursively merges configuration data, with values from
        other config taking precedence over existing values.
        
        Parameters:
        - other: Config - Configuration to merge
        """
    
    def collisions(self, other):
        """
        Find colliding keys with another config.
        
        Returns dictionary of keys that exist in both configs
        with different values.
        
        Parameters:
        - other: Config - Configuration to compare
        
        Returns:
        dict - Colliding keys and values
        """

class LazyConfigValue:
    """
    Lazy evaluation of config values.
    
    Defers evaluation of configuration values until they are
    actually needed, enabling complex configuration expressions.
    """

Configuration Loaders

Classes for loading configuration from various sources.

class ConfigLoader:
    """Base class for configuration loaders."""
    
    def load_config(self):
        """
        Load configuration data.
        
        Returns:
        Config - Loaded configuration object
        """

class FileConfigLoader(ConfigLoader):
    """Base class for file-based configuration loaders."""

class JSONFileConfigLoader(FileConfigLoader):
    """
    Load configuration from JSON files.
    
    Supports loading configuration data from JSON format files
    with automatic type conversion and validation.
    """

class PyFileConfigLoader(FileConfigLoader):
    """
    Load configuration from Python files.
    
    Executes Python configuration files and extracts configuration
    objects, allowing for dynamic configuration generation.
    """

class CommandLineConfigLoader(ConfigLoader):
    """Base class for command line configuration loaders."""

class KeyValueConfigLoader(CommandLineConfigLoader):
    """
    Load configuration from key-value pairs.
    
    Processes command line arguments in key=value format
    and converts them to configuration data.
    """

class ArgParseConfigLoader(CommandLineConfigLoader):
    """
    Load configuration using argparse.
    
    Integrates with Python's argparse module for sophisticated
    command line argument processing.
    """

class KVArgParseConfigLoader(ArgParseConfigLoader):
    """
    Key-value argparse configuration loader.
    
    Combines argparse functionality with key-value configuration
    for flexible command line processing.
    """

Configuration Exceptions

Exception classes for configuration errors.

class ConfigError(Exception):
    """Base exception for configuration errors."""

class ConfigLoaderError(ConfigError):
    """Exception raised by configuration loaders."""

class ConfigFileNotFound(ConfigLoaderError):
    """Exception raised when configuration file is not found."""

class ArgumentError(ConfigLoaderError):
    """Exception raised for command line argument errors."""

Configuration Manager

Classes for managing configuration persistence.

class BaseJSONConfigManager:
    """
    JSON configuration file manager.
    
    Provides methods for storing and retrieving configuration
    data in JSON format with atomic file operations.
    """
    
    def get(self, section_name):
        """
        Retrieve configuration data for a section.
        
        Parameters:
        - section_name: str - Configuration section name
        
        Returns:
        dict - Configuration data for the section
        """
    
    def set(self, section_name, data):
        """
        Store configuration data for a section.
        
        Parameters:
        - section_name: str - Configuration section name
        - data: dict - Configuration data to store
        """
    
    def update(self, section_name, new_data):
        """
        Update configuration section with new data.
        
        Merges new data with existing configuration data
        for the specified section.
        
        Parameters:
        - section_name: str - Configuration section name
        - new_data: dict - New data to merge
        """

Configuration Utilities

Utility functions for configuration management.

def catch_config_error(method):
    """
    Decorator for catching configuration errors during initialization.
    
    Wraps methods to catch and handle configuration errors gracefully,
    typically used on Application.initialize methods.
    
    Parameters:
    - method: callable - Method to wrap
    
    Returns:
    callable - Decorated method
    """

def boolean_flag(name, configurable, set_help='', unset_help=''):
    """
    Helper for building --trait/--no-trait flag pairs.
    
    Creates a dictionary of command line flags for boolean traits
    that can be used in Application.flags.
    
    Parameters:
    - name: str - Flag name
    - configurable: str - Configurable class name
    - set_help: str - Help text for --flag
    - unset_help: str - Help text for --no-flag
    
    Returns:
    dict - Flag configuration dictionary
    """

def get_config():
    """
    Get configuration object for global Application instance.
    
    Returns the configuration from the currently running Application
    instance, if one exists.
    
    Returns:
    Config|None - Global application configuration
    """

def recursive_update(target, new):
    """
    Recursively update dictionaries.
    
    Deep merge two dictionaries, updating nested structures
    while preserving existing keys not in the new dictionary.
    
    Parameters:
    - target: dict - Dictionary to update
    - new: dict - New values to merge
    """

Usage Examples

Basic Application

from traitlets.config import Application
from traitlets import Unicode, Int, Bool

class MyApp(Application):
    name = Unicode(u'myapp')
    description = Unicode(u'A sample configurable application')
    version = Unicode(u'1.0.0')
    
    # Configurable traits
    host = Unicode(u'localhost', help="Server host").tag(config=True)
    port = Int(8080, help="Server port").tag(config=True)
    debug = Bool(False, help="Debug mode").tag(config=True)
    
    # Command line aliases
    aliases = {
        'host': 'MyApp.host',
        'port': 'MyApp.port',
    }
    
    # Command line flags
    flags = {
        'debug': ({'MyApp': {'debug': True}}, "Enable debug mode"),
    }
    
    def start(self):
        print(f"Starting {self.name} v{self.version}")
        print(f"Host: {self.host}")
        print(f"Port: {self.port}")
        print(f"Debug: {self.debug}")

if __name__ == '__main__':
    MyApp.launch_instance()

Configuration Files

Python configuration file (myapp_config.py):

c = get_config()

c.MyApp.host = '0.0.0.0'
c.MyApp.port = 9000
c.MyApp.debug = True

JSON configuration file (myapp_config.json):

{
  "MyApp": {
    "host": "0.0.0.0",
    "port": 9000,
    "debug": true
  }
}

Configurable Classes

from traitlets.config import Configurable
from traitlets import Unicode, Int, List

class DatabaseConfig(Configurable):
    host = Unicode(u'localhost', help="Database host").tag(config=True)
    port = Int(5432, help="Database port").tag(config=True)  
    username = Unicode(help="Database username").tag(config=True)
    databases = List(Unicode(), help="Database names").tag(config=True)

class WebConfig(Configurable):
    bind_host = Unicode(u'127.0.0.1', help="Web server bind host").tag(config=True)
    bind_port = Int(8000, help="Web server bind port").tag(config=True)
    static_path = Unicode(u'./static', help="Static files path").tag(config=True)

class MyApplication(Application):
    classes = [DatabaseConfig, WebConfig]
    
    aliases = {
        'db-host': 'DatabaseConfig.host',
        'db-port': 'DatabaseConfig.port',
        'web-host': 'WebConfig.bind_host',
        'web-port': 'WebConfig.bind_port',
    }

# Usage: python myapp.py --db-host=db.example.com --web-port=9000

Configuration Manager

from traitlets.config.manager import BaseJSONConfigManager
import tempfile
import os

# Create temporary config directory
config_dir = tempfile.mkdtemp()
config_manager = BaseJSONConfigManager(config_dir=config_dir)

# Store configuration
app_config = {
    'host': 'example.com',
    'port': 8080,
    'features': ['auth', 'logging']
}

config_manager.set('myapp', app_config)

# Retrieve configuration
loaded_config = config_manager.get('myapp')
print(loaded_config)  # {'host': 'example.com', 'port': 8080, 'features': ['auth', 'logging']}

# Update configuration
config_manager.update('myapp', {'debug': True, 'port': 9000})

updated_config = config_manager.get('myapp')
print(updated_config)  # Includes debug=True and port=9000

# Cleanup
import shutil
shutil.rmtree(config_dir)

Advanced Application with Subcommands

from traitlets.config import Application
from traitlets import Unicode, List, Dict

class SubcommandApp(Application):
    name = Unicode(u'myapp')
    
    subcommands = Dict({
        'init': ('myapp.InitCommand', "Initialize new project"),
        'serve': ('myapp.ServeCommand', "Start web server"),  
        'deploy': ('myapp.DeployCommand', "Deploy application"),
    })
    
    def start(self):
        if self.subapp:
            self.subapp.start()
        else:
            self.print_help()

class InitCommand(Application):
    name = Unicode(u'init')
    project_name = Unicode(help="Project name").tag(config=True)
    
    aliases = {'name': 'InitCommand.project_name'}
    
    def start(self):
        print(f"Initializing project: {self.project_name}")

class ServeCommand(Application):
    name = Unicode(u'serve')
    host = Unicode(u'localhost').tag(config=True)
    port = Int(8000).tag(config=True)
    
    def start(self):
        print(f"Serving on {self.host}:{self.port}")

# Usage:
# python myapp.py init --name=myproject
# python myapp.py serve --port=9000

Custom Configuration Loader

from traitlets.config.loader import ConfigLoader
from traitlets.config import Config
import yaml

class YAMLConfigLoader(ConfigLoader):
    def __init__(self, filename):
        self.filename = filename
    
    def load_config(self):
        with open(self.filename, 'r') as f:
            data = yaml.safe_load(f)
        
        config = Config()
        for section, values in data.items():
            config[section] = values
            
        return config

# Usage with Application
class YAMLApp(Application):
    def load_config_file(self, filename, path=None):
        if filename.endswith('.yaml') or filename.endswith('.yml'):
            loader = YAMLConfigLoader(filename)
            config = loader.load_config()
            self.config.merge(config)
        else:
            super().load_config_file(filename, path)

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