### Install Hatch and Build Docs Source: https://github.com/ipython/traitlets/blob/main/docs/readme-docs.md Installs hatch and then runs the documentation build process. ```bash pip install hatch hatch run docs:build ``` -------------------------------- ### Create Virtual Environment and Install Dependencies Source: https://github.com/ipython/traitlets/blob/main/docs/readme-docs.md Creates a dedicated virtual environment for building documentation and installs the necessary dependencies, including those for docs. ```bash virtualenv traitlets_docs -p python3 pip install -r traitlets[docs] ``` -------------------------------- ### Install Traitlets Source: https://github.com/ipython/traitlets/blob/main/README.md Install the Traitlets library using pip. This is the standard installation method. ```bash pip install traitlets ``` -------------------------------- ### Example Bash Command Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Illustrates how to launch a subcommand, in this case, the QtConsole, with a specific profile. ```bash $ jupyter qtconsole --profile myprofile ``` -------------------------------- ### Launch Application with Command-line Arguments Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Use `launch_instance()` to create an application, parse command-line arguments, and start the application. The `start` method contains the application's core logic. ```python from traitlets.config import Application class MyApp(Application): def start(self): pass # app logic goes here if __name__ == "__main__": MyApp.launch_instance() ``` -------------------------------- ### Starting Multiple Applications Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Illustrates how to start multiple applications, even when they inherit from `Application`, by manually creating and initializing instances. This bypasses the singleton pattern for nested applications. ```python from traitlets.config import Application class OtherApp(Application): def start(self): print("other") class MyApp(Application): classes = [OtherApp] def start(self): # similar to OtherApp.launch_instance(), but without singleton self.other_app = OtherApp(config=self.config) self.other_app.initialize(["--OtherApp.log_level", "INFO"]) self.other_app.start() if __name__ == "__main__": MyApp.launch_instance() ``` -------------------------------- ### Run Traitlets Tests Source: https://github.com/ipython/traitlets/blob/main/README.md Install test dependencies and run the test suite using py.test. Ensure your installation is working correctly. ```bash pip install "traitlets[test]" py.test traitlets ``` -------------------------------- ### Install Pre-commit Hook Source: https://github.com/ipython/traitlets/blob/main/README.md Install the pre-commit tool to manage code formatting and hooks. This ensures consistent code style. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Command-line Argument Example Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Demonstrates how to set configuration values directly from the command line using the `--Class.trait=value` format. This overrides values from configuration files. ```bash $ ipython --InteractiveShell.autoindent=False --BaseIPythonApplication.profile='myprofile' ``` -------------------------------- ### Serve Documentation Locally with Python 3 HTTP Server Source: https://github.com/ipython/traitlets/blob/main/docs/readme-docs.md Starts a local HTTP server on port 8000 to display the built documentation. Access it via http://localhost:8000 in your browser. ```bash python -m http.server 8000 ``` -------------------------------- ### Defining Flags for Configuration Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Provides an example of defining flags for controlling application configuration in Python. ```python from traitlets import Bool from traitlets.config import Application, Configurable class Foo(Configurable): enabled = Bool(False, help="whether enabled").tag(config=True) class App(Application): classes = [Foo] dry_run = Bool(False, help="dry run test").tag(config=True) flags = { "dry-run": ({"App": {"dry_run": True}}, dry_run.help), ("f", "enable-foo"): ( { "Foo": {"enabled": True}, }, "Enable foo", ), ("disable-foo"): ({"Foo": {"enabled": False}}, "Disable foo", ), } if __name__ == "__main__": App.launch_instance() ``` -------------------------------- ### JSON Configuration File Example Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Represent configuration settings in a JSON file. This format is useful for programmatic generation and processing. The structure mirrors the Python configuration syntax. ```json { "School": { "name": "coolname", "ranking": 10 } } ``` -------------------------------- ### Development Installation of Traitlets Source: https://github.com/ipython/traitlets/blob/main/README.md Install Traitlets in development mode by cloning the repository and using pip. This allows for direct code modifications and testing. ```bash git clone https://github.com/ipython/traitlets.git cd traitlets pip install -e . ``` -------------------------------- ### Load Configuration from Python and JSON Files Source: https://context7.com/ipython/traitlets/llms.txt Demonstrates using `PyFileConfigLoader` and `JSONFileConfigLoader` to load application configurations. Includes examples of Python config files with `get_config()` and JSON config files. ```python # --- myapp_config.py (Python config file) --- c = get_config() # noqa: F821 -- injected by the loader c.Processor.workers = 16 c.Processor.verbose = True c.MyApp.log_level = "INFO" # --- myapp_config.json (JSON config file) --- # { # "Processor": { # "workers": 16, # "verbose": true # }, # "MyApp": { # "log_level": "INFO" # } # } # Loading a config file from Python: from traitlets.config.loader import PyFileConfigLoader, JSONFileConfigLoader, Config # Load a Python config file loader = PyFileConfigLoader("myapp_config.py", path=["/etc/myapp", "~/.myapp"]) try: cfg = loader.load_config() print(cfg.Processor.workers) # 16 except Exception as e: print(f"Config file not found or invalid: {e}") # Load a JSON config file loader2 = JSONFileConfigLoader("myapp_config.json", path=["~/.myapp"]) try: cfg2 = loader2.load_config() print(cfg2.Processor.verbose) # True except Exception as e: print(f"Config file not found or invalid: {e}") # Merging configs (later values win) base_cfg = Config() base_cfg.Processor.workers = 4 override = Config() override.Processor.workers = 8 base_cfg.merge(override) print(base_cfg.Processor.workers) # 8 # Application.load_config_environ() reads env vars like # MYAPP_PROCESSOR_WORKERS=16 (varies by application) ``` -------------------------------- ### Install Release Tools Source: https://github.com/ipython/traitlets/blob/main/RELEASE.md Installs necessary tools for building and releasing Python packages. Ensure you are on the latest version of your current branch before proceeding. ```bash pip install hatch twine build git pull origin $(git branch --show-current) git clean -dffx ``` -------------------------------- ### JSON File Configuration Loading Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Example of using `JSONFileConfigLoader` as a context manager to load and update configuration from a JSON file. ```python with JSONFileConfigLoader('myapp.json','/home/jupyter/configurations/') as c: c.MyNewConfigurable.new_value = 'Updated' ``` -------------------------------- ### Alias Example: --profile Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Shows a common alias usage, where `--profile myprofile` is a shorthand for setting a specific profile. ```bash $ ipython --profile myprofile ``` -------------------------------- ### Define a Traitlets Application with CLI Parsing Source: https://context7.com/ipython/traitlets/llms.txt Shows how to create a custom application subclassing `traitlets.config.application.Application`. It includes defining configurable classes, aliases, flags, and implementing `initialize` and `start` methods. ```python from traitlets import Bool, Unicode, List, Dict, Int from traitlets.config.application import Application from traitlets.config.configurable import Configurable class Processor(Configurable): workers = Int(4, help="Number of worker threads").tag(config=True) verbose = Bool(False, help="Verbose output").tag(config=True) class MyApp(Application): name = Unicode("myapp") description = Unicode("A demo traitlets Application.") # Configurable classes exposed to config system and --help-all classes = List([Processor]) # Short aliases: --workers=N maps to Processor.workers aliases = Dict({ "w": "Processor.workers", "workers": "Processor.workers", "log-level": "MyApp.log_level", }) # Flags: --verbose sets Processor.verbose=True flags = Dict({ "verbose": ({"Processor": {"verbose": True}}, "Enable verbose output"), "debug": ({"MyApp": {"log_level": 10}}, "Set log level to DEBUG"), }) config_file = Unicode("", help="Path to a config file").tag(config=True) def initialize(self, argv=None): self.parse_command_line(argv) if self.config_file: self.load_config_file(self.config_file) self.processor = Processor(parent=self) def start(self): self.log.info("Starting with %d workers", self.processor.workers) if self.processor.verbose: print("Verbose mode is ON") print(f"Config: {self.config}") # Programmatic usage (equivalent to running from CLI) app = MyApp() app.initialize(["--workers=8", "--verbose"]) # app.start() # CLI usage (from a script): # python myapp.py --workers=4 --verbose --log-level=INFO # python myapp.py --Processor.workers=2 --MyApp.log_level=DEBUG # Generate a config file template: # print(app.generate_config_file()) if __name__ == "__main__": MyApp.launch_instance() ``` -------------------------------- ### FuzzyEnum and UseEnum Examples Source: https://context7.com/ipython/traitlets/llms.txt Demonstrates unique prefix matching for enums and multiple assignment styles for enum values. ```python c.output_fmt = "js" # matches "json" (unique prefix) c.output_fmt = "ts" # matches "tsv" print(c.output_fmt) # tsv # UseEnum: multiple assignment styles c.color = Color.BLUE c.color = "GREEN" # name as string c.color = "Color.RED" # scoped name c.color = 2 # integer value → Color.GREEN print(c.color) # Color.GREEN ``` -------------------------------- ### Application with List and Dict traits Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Defines an `Application` with `List` and `Dict` traits, demonstrating how to configure them using aliases and multiple command-line arguments. This example shows the practical application of the new container trait handling. ```python from traitlets.config import Application from traitlets import Dict, Integer, List, Unicode class App(Application): aliases = {"x": "App.x", "y": "App.y"} x = List(Unicode(), config=True) y = Dict(Integer(), config=True) def start(self): print(f"x={self.x}") print(f"y={self.y}") if __name__ == "__main__": App.launch_instance() ``` ```bash $ examples/docs/container.py -x a -x b -y a=10 -y b=5 x=['a', 'b'] y={'a': 10, 'b': 5} ``` -------------------------------- ### Activate Global Python Argcomplete Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Instructions for setting up global tab completion for Python scripts using argcomplete. This involves installing the package, creating a destination directory, and sourcing the completion script. ```bash # pip install argcomplete mkdir -p ~/.bash_completion.d/ activate-global-python-argcomplete --dest=~/.bash_completion.d/argcomplete # source ~/.bash_completion.d/argcomplete from your ~/.bashrc ``` -------------------------------- ### Python Configuration File Example Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Set configurable attributes for a class in a Python configuration file. The `c` object represents the configuration, and attributes are set using the `c.ClassName.attribute_name = value` syntax. ```python # Sample config file c.School.name = "coolname" c.School.ranking = 10 ``` -------------------------------- ### Configure Logging with File Handler Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md This example demonstrates how to add a file handler to the logging configuration. Ensure the application name in the logger configuration matches your application's name. If you omit the default 'console' handler from the logger's handler list, it will be disabled. ```python c.Application.logging_config = { "handlers": { "file": { "class": "logging.FileHandler", "level": "DEBUG", "filename": "", } }, "loggers": { "": { "level": "DEBUG", # NOTE: if you don't list the default "console" # handler here then it will be disabled "handlers": ["console", "file"], }, }, } ``` -------------------------------- ### traitlets.UseEnum Example Source: https://github.com/ipython/traitlets/blob/main/docs/source/trait_types.md Demonstrates how to use the UseEnum trait type with an enum class. It shows different ways to assign values to the trait, including Enum values, names, scoped names, and numbers. ```APIDOC ## traitlets.UseEnum Example ### Description This example demonstrates the usage of `traitlets.UseEnum` with a Python `enum.Enum` class. It illustrates how to define a trait that accepts values from an enumeration and shows various valid ways to assign values to this trait, including using the enum member directly, its name as a string, its scoped name as a string, or its underlying integer value. ### Code Example ```python # -- SINCE: Python 3.4 (or install backport: pip install enum34) import enum from traitlets import HasTraits, UseEnum class Color(enum.Enum): red = 1 # -- IMPLICIT: default_value blue = 2 green = 3 class MyEntity(HasTraits): color = UseEnum(Color, default_value=Color.blue) entity = MyEntity(color=Color.red) entity.color = Color.green # USE: Enum-value (preferred) entity.color = "green" # USE: name (as string) entity.color = "Color.green" # USE: scoped-name (as string) entity.color = 3 # USE: number (as int) assert entity.color is Color.green ``` ### Parameters This snippet does not directly expose parameters in a structured format but demonstrates the usage within a Python class definition. ``` -------------------------------- ### Command-line Argument Equivalents Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Demonstrates how command-line arguments can be mapped to application configuration. ```bash $ ipython --profile='myprofile' # are equivalent to $ ipython --BaseIPythonApplication.profile='myprofile' ``` -------------------------------- ### Create and Retrieve Singleton Instance Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Demonstrates how to create a singleton class using `instance()` and verify that subsequent calls return the same instance. ```python >>> from traitlets.config.configurable import SingletonConfigurable >>> class Foo(SingletonConfigurable): pass >>> foo = Foo.instance() >>> foo == Foo.instance() True ``` -------------------------------- ### Configuration File Equivalent Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Shows the equivalent configuration settings in a config file for the command-line arguments provided. ```python c.InteractiveShell.autoindent = False c.BaseIPythonApplication.profile = "myprofile" ``` -------------------------------- ### TraitError Message for Type Mismatch Source: https://github.com/ipython/traitlets/blob/main/docs/source/using_traitlets.md This is an example of a `TraitError` that occurs when a value of the wrong type is assigned to a trait. ```default TraitError: The 'bar' trait of a Foo instance must be an int, but a value of '3' was specified ``` -------------------------------- ### Command-line Flag Equivalents Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Illustrates how command-line flags can be used to set configuration values. ```bash $ ipcontroller --debug # is equivalent to $ ipcontroller --Application.log_level=DEBUG # and $ ipython --matplotlib # is equivalent to $ ipython --matplotlib auto # or $ ipython --no-banner # is equivalent to $ ipython --TerminalIPythonApp.display_banner=False ``` -------------------------------- ### Build Documentation with make.bat (Windows) Source: https://github.com/ipython/traitlets/blob/main/docs/readme-docs.md Builds the HTML documentation using the make.bat script, intended for Windows systems. ```bash make.bat html ``` -------------------------------- ### Application Initialization and Launch Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Methods for initializing and launching the application. ```APIDOC ## initialize(argv: List[str] | None = None) -> None Do the basic steps to configure me. Override in subclasses. ## initialize_subcommand(subc: str, argv: List[str] | None = None) -> None Initialize a subcommand with argv. ## *classmethod* launch_instance(argv: List[str] | None = None, **kwargs: Any) -> None Launch a global instance of this Application If a global instance already exists, this reinitializes and starts it ## parse_command_line(argv: List[str] | None = None) -> None Parse the command line arguments. ## start() -> None Start the app mainloop. Override in subclasses. ``` -------------------------------- ### traitlets.config.LoggingConfigurable Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md A parent class for Configurables that log. Subclasses have a log trait, and the default behavior is to get the logger from the currently running Application. ```APIDOC ## class traitlets.config.LoggingConfigurable(*args: t.Any, **kwargs: t.Any) ### Description A parent class for Configurables that log. Subclasses have a log trait, and the default behavior is to get the logger from the currently running Application. ### Traits #### log Logger or LoggerAdapter instance. ``` -------------------------------- ### Build Documentation with Makefile (Linux/OS X) Source: https://github.com/ipython/traitlets/blob/main/docs/readme-docs.md Builds the HTML documentation using the Makefile, typically on Linux or macOS systems. ```bash make html ``` -------------------------------- ### Programmatically Build and Use a Config Object Source: https://context7.com/ipython/traitlets/llms.txt Demonstrates creating a Config object, setting attributes on configurables, and instantiating them. Also shows parent propagation where a child inherits its parent's configuration. ```python from traitlets import Config, Configurable, Int, Unicode # Mock classes for demonstration class Database(Configurable): host = Unicode("localhost").tag(config=True) port = Int(5432).tag(config=True) poolsize = Int(10).tag(config=True) class App(Configurable): name = Unicode("default").tag(config=True) # Build a Config object programmatically c = Config() c.Database.host = "db.prod.example.com" c.Database.port = 5433 c.Database.poolsize = 20 c.App.name = "production" # Instantiate configurables from the config db = Database(config=c) app = App(config=c) print(db.host) # db.prod.example.com print(db.port) # 5433 print(app.name) # production # Parent propagation: child inherits parent's config class Worker(Configurable): threads = Int(2).tag(config=True) class Manager(Configurable): name = Unicode("manager").tag(config=True) def __init__(self, **kwargs): super().__init__(**kwargs) # parent=self passes config automatically self.worker = Worker(parent=self) c2 = Config() c2.Worker.threads = 8 mgr = Manager(config=c2) print(mgr.worker.threads) # 8 ``` -------------------------------- ### Navigate to Docs Directory Source: https://github.com/ipython/traitlets/blob/main/docs/readme-docs.md Changes the current directory to the 'docs' folder to prepare for manual documentation building. ```bash cd docs ``` -------------------------------- ### Trait Type Checking and Coercion Example Source: https://github.com/ipython/traitlets/blob/main/docs/source/using_traitlets.md Traitlets enforce type checking. Assigning a value of an incompatible type will raise a `TraitError`, even if the value could be coerced. ```python class Foo(HasTraits): bar = Int() foo = Foo(bar="3") # raises a TraitError ``` -------------------------------- ### Load Configuration from Arguments Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Illustrates loading configuration by parsing command-line arguments using KVArgParseConfigLoader. The flags parameter is deprecated. ```python config = loader.load_config(argv=None, aliases=None, flags=None, classes=None) ``` -------------------------------- ### Create and Assign Config Values Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Demonstrates creating a Config object and assigning values to traits, including appending to lists. ```python c = Config() c.Class.int_trait = 5 c.Class.list_trait.append("x") ``` -------------------------------- ### Linking Traits for Synchronization Source: https://context7.com/ipython/traitlets/llms.txt Demonstrates bidirectional linking with `link` and unidirectional linking with `dlink` for synchronizing trait values between objects. Includes examples of transform callables for type conversion and unlinking. ```python from traitlets import HasTraits, Int, Float, Unicode, link, dlink class Slider(HasTraits): value = Int(0) class Label(HasTraits): text = Unicode("0") class Display(HasTraits): value = Float(0.0) slider = Slider() label = Label() display = Display() # Bidirectional link: slider.value <-> label.text # transform=(forward, inverse) convert between types lnt = link( (slider, "value"), (label, "text"), transform=(str, int) ) slider.value = 42 print(label.text) # "42" label.text = "10" print(slider.value) # 10 # Unlink when done lnt.unlink() # Directional link: slider.value -> display.value (not reversed) dlnkt = dlink( (slider, "value"), (display, "value"), transform=float ) slider.value = 7 print(display.value) # 7.0 display.value = 99.9 # does NOT change slider print(slider.value) # 7 (unchanged) dlnkt.unlink() ``` -------------------------------- ### Instance, Type, This Trait Examples Source: https://context7.com/ipython/traitlets/llms.txt Illustrates Instance for validating object types, Type for validating class types, and This for self-referential traits. Includes lazy loading via string import paths and default factory methods. ```python from traitlets import HasTraits, Instance, Type, This, Unicode, default import logging class Node(HasTraits): name = Unicode("node") parent = This() # must be a Node (or None) child = This() # same log = Instance(logging.Logger, allow_none=True) # Type trait: stores a class (subclass of dict) storage_class = Type(dict) @default("log") def _default_log(self): return logging.getLogger(self.name) root = Node(name="root") child = Node(name="child") child.parent = root # OK: root is a Node root.child = child try: root.parent = "not a node" # TraitError except Exception as e: print(e) # Type trait n = Node() n.storage_class = dict # default n.storage_class = type("MyDict", (dict,), {}) # Instance with string path (resolved lazily) class Server(HasTraits): handler = Instance("logging.Handler", allow_none=True) ``` -------------------------------- ### Dict Trait Validation Source: https://context7.com/ipython/traitlets/llms.txt Demonstrates the use of Dict traits for validating dictionary values, with options for constraining key types, value types, or specific keys using per_key_traits. Includes examples of type errors for values and keys. ```python from traitlets import HasTraits, Dict, Unicode, Int, Bool class AppConfig(HasTraits): # Values must be unicode strings env_vars = Dict(Unicode(), default_value={}) # Keys must be Unicode, values must be Int scores = Dict(value_trait=Int(), key_trait=Unicode(), default_value={}) # Per-key type constraints settings = Dict(per_key_traits={"debug": Bool(), "workers": Int(), "name": Unicode()}) cfg = AppConfig() cfg.env_vars = {"HOME": "/home/user", "PATH": "/usr/bin"} try: cfg.env_vars = {"key": 42} # TraitError: value must be unicode except Exception as e: print(e) cfg.scores = {"alice": 95, "bob": 87} try: cfg.scores = {"alice": "A+"} # TraitError: value must be int except Exception as e: print(e) cfg.settings = {"debug": True, "workers": 4, "name": "prod"} print(cfg.settings) ``` -------------------------------- ### Define Subcommands in Application Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Shows how to define subcommands for an Application. It maps subcommand names to Application subclasses or factory functions and their descriptions. ```python from traitlets.config import Application class SubApp1(Application): pass class SubApp2(Application): @classmethod def get_subapp_instance(cls, app: Application) -> Application: app.clear_instance() # since Application is singleton, need to clear main app return cls.instance(parent=app) class MainApp(Application): subcommands = { "subapp1": (SubApp1, "First subapp"), "subapp2": (SubApp2.get_subapp_instance, "Second subapp"), } if __name__ == "__main__": MainApp.launch_instance() ``` -------------------------------- ### Initialize KVArgParseConfigLoader Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Shows how to initialize KVArgParseConfigLoader with various options like aliases, flags, and classes for parsing command-line arguments. ```python loader = KVArgParseConfigLoader(argv=None, aliases=None, flags=None, log=None, classes=None, subcommands=None, *parser_args, **parser_kw) ``` -------------------------------- ### traitlets.config.Application Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md A singleton application with full configuration support. Provides methods for generating documentation and emitting help information. ```APIDOC ## class traitlets.config.Application(*args: t.Any, **kwargs: t.Any) ### Description A singleton application with full configuration support. ### Traits #### cli_config The subset of our configuration that came from the command-line. We re-load this configuration after loading config files, to ensure that it maintains highest priority. ### Methods #### document_config_options() Generate rST format documentation for the config options this application. Returns a multiline string. #### emit_alias_help() Yield the lines for alias part of the help. #### emit_description() Yield lines with the application description. #### emit_examples() Yield lines with the usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application’s usage. #### emit_flag_help() Yield the lines for the flag part of the help. #### emit_help(classes: bool = False) Yield the help-lines for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. ``` -------------------------------- ### Defining Aliases for Configuration Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Shows how to define aliases for configuration traits in Python applications. ```python from traitlets import Bool from traitlets.config import Application, Configurable class Foo(Configurable): enabled = Bool(False, help="whether enabled").tag(config=True) class App(Application): classes = [Foo] dry_run = Bool(False, help="dry run test").tag(config=True) aliases = { "dry-run": "App.dry_run", ("f", "foo-enabled"): ("Foo.enabled", "whether foo is enabled"), } if __name__ == "__main__": App.launch_instance() ``` -------------------------------- ### Build Distribution Artifacts Source: https://github.com/ipython/traitlets/blob/main/RELEASE.md Removes any existing distribution files and then builds new artifacts (e.g., source distributions, wheels) using the 'build' package. This prepares the package for distribution. ```bash rm -rf dist python -m build . ``` -------------------------------- ### Registering Subcommands in Traitlets Application Source: https://context7.com/ipython/traitlets/llms.txt Define subcommands for an Application by registering them as a dictionary on `Application.subcommands`. Each entry maps a subcommand name to a tuple containing the class or factory and a description. ```python from traitlets import Unicode from traitlets.config.application import Application class ServeApp(Application): name = Unicode("myapp-serve") description = Unicode("Start the HTTP server.") def start(self): print("Serving...") class MigrateApp(Application): name = Unicode("myapp-migrate") description = Unicode("Run database migrations.") def start(self): print("Migrating...") class MainApp(Application): name = Unicode("myapp") description = Unicode("Main entry point.") subcommands = { "serve": (ServeApp, "Start the HTTP server"), "migrate": (MigrateApp, "Run database migrations"), } def start(self): if self.subapp: self.subapp.start() else: self.print_help() # CLI usage: # python main.py serve # python main.py migrate --help if __name__ == "__main__": MainApp.launch_instance() ``` -------------------------------- ### Dynamic Trait Management with add_traits and has_trait Source: https://context7.com/ipython/traitlets/llms.txt Explains how to add traits to an instance at runtime using `add_traits` and check for trait existence with `has_trait`. Also shows how to enumerate traits using `traits` and `trait_names`, with filtering by metadata. ```python from traitlets import HasTraits, Int, Unicode, Float class Expandable(HasTraits): name = Unicode("base") obj = Expandable() print(obj.has_trait("name")) # True print(obj.has_trait("extra")) # False # Dynamically add a new trait obj.add_traits(score=Float(0.0)) print(obj.has_trait("score")) # True obj.score = 9.5 print(obj.score) # 9.5 # traits() with metadata filtering from traitlets import HasTraits, Int, Unicode class Tagged(HasTraits): public = Int(0).tag(config=True, sync=True) internal = Int(0) label = Unicode("").tag(config=True) t = Tagged() # Get only config=True traits config_traits = t.traits(config=True) print(sorted(config_traits)) # ['label', 'public'] # Get traits where sync=True sync_traits = t.traits(sync=True) print(sorted(sync_traits)) # ['public'] ``` -------------------------------- ### Load Sub-configuration File Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Use `load_subconfig()` to inherit settings from another Python configuration file. Ensure the sub-config file is in the search path, typically the same directory. ```python c = get_config() # noqa c.School.name = "Harvard" c.School.ranking = 100 ``` ```python c = get_config() # noqa # Load everything from base_config.py load_subconfig("base_config.py") # noqa # Now override one of the values c.School.name = "bettername" ``` -------------------------------- ### Run Pre-commit Hooks Manually Source: https://github.com/ipython/traitlets/blob/main/README.md Manually invoke pre-commit hooks to format code and check for style errors. Use '--all-files' to format the entire repository. ```bash pre-commit run pre-commit run --all-files ``` -------------------------------- ### traitlets.List.from_string_list Source: https://github.com/ipython/traitlets/blob/main/docs/source/trait_types.md Parses configuration from a list of strings, typically used for command-line arguments. ```APIDOC ## traitlets.List.from_string_list ### Description Return the value from a list of config strings. This is where we parse CLI configuration. ### Method from_string_list ### Parameters #### Path Parameters - **s_list** (list[str]) - Required - A list of configuration strings. ### Response #### Success Response (200) - **T | None** - The parsed value or None if parsing fails. ``` -------------------------------- ### Configuration Loading and Generation Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Methods for loading and generating configuration files. ```APIDOC ## flatten_flags() -> tuple[dict[str, Any], dict[str, Any]] Flatten flags and aliases for loaders, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect `(key: longname)` and not `key: (longname, help)` items. Only aliases with exactly one descendent in the class list will be promoted. ## generate_config_file(classes: List[Type[[Configurable](#traitlets.config.Configurable)]] | None = None) -> str generate default config file from Configurables ## load_config_environ() -> None Load config files by environment. ## load_config_file(filename: str, path: str | Sequence[str | None] | None = None) -> None Load config files by filename and path. ``` -------------------------------- ### Configuration Display Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Methods for displaying configuration information. ```APIDOC ## show_config Instead of starting the Application, dump configuration to stdout ## show_config_json Instead of starting the Application, dump configuration to stdout (as JSON) ``` -------------------------------- ### Using TraitType Descriptors Source: https://context7.com/ipython/traitlets/llms.txt Explains the `TraitType` base class and its common constructor arguments like `default_value`, `allow_none`, `read_only`, and `help`. It also demonstrates the `tag()` method for metadata and the `set_trait()` method. ```APIDOC ## TraitType — Base descriptor for all trait types `TraitType` is the base class from which every concrete trait type inherits. It exposes the `tag()` method for attaching arbitrary metadata, the `allow_none` and `read_only` flags, and `from_string()` for CLI parsing. All constructors accept `default_value`, `allow_none`, `read_only`, and `help`. ```python from traitlets import HasTraits, Int, Unicode, Float class Config(HasTraits): # read_only=True prevents direct assignment version = Unicode("1.0", read_only=True, help="Library version") # allow_none=True makes None a valid value timeout = Float(30.0, allow_none=True, help="Request timeout in seconds") # .tag() attaches arbitrary metadata (config=True is used by the config system) max_conn = Int(10, help="Max connections").tag(config=True, sync=True) cfg = Config() print(cfg.max_conn) # 10 # Read metadata trait = Config.class_traits()["max_conn"] print(trait.metadata) # {'config': True, 'sync': True, 'help': 'Max connections'} print(trait.help) # Max connections print(trait.allow_none) # False print(trait.read_only) # False cfg.timeout = None # OK because allow_none=True print(cfg.timeout) # None try: cfg.version = "2.0" # raises TraitError: trait is read_only except Exception as e: print(e) # set_trait() bypasses read_only cfg.set_trait("version", "2.0") print(cfg.version) # 2.0 # Check whether a value has been explicitly set (vs. still at default) print(cfg.trait_has_value("timeout")) # True (we assigned None) ``` ``` -------------------------------- ### Command-line string parsing Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Demonstrates how traitlets 5.0 handles command-line string parsing using `from_string()`, which defers interpretation until the target trait type is known. This avoids issues with ambiguous literals and reduces the need for double-quoting. ```bash $ ipython -c 1 ... [TerminalIPythonApp] CRITICAL | Bad config encountered during initialization: [TerminalIPythonApp] CRITICAL | The 'code_to_run' trait of a TerminalIPythonApp instance must be a unicode string, but a value of 1 was specified. ``` ```bash $ ipython -c "'1'" ``` -------------------------------- ### Callable and Any Traits for Unconstrained Values Source: https://context7.com/ipython/traitlets/llms.txt Shows how to use Callable for functions/methods and Any for any Python object. Callable requires the value to be callable, while Any accepts any type. ```python from traitlets import HasTraits, Callable, Any class Pipeline(HasTraits): transform = Callable(allow_none=True) metadata = Any(default_value=None) p = Pipeline() # Callables p.transform = lambda x: x * 2 p.transform = print p.transform = int # classes are callable try: p.transform = 42 # TraitError: not callable except Exception as e: print(e) # Any accepts anything p.metadata = {"key": [1, 2, 3]} p.metadata = object() p.metadata = None p.metadata = 42 ``` -------------------------------- ### Publish to PyPI Source: https://github.com/ipython/traitlets/blob/main/RELEASE.md Checks the distribution artifacts for integrity using 'twine check' and then uploads them to the Python Package Index (PyPI) using 'twine upload'. This makes the release available to users. ```bash twine check dist/* twine upload dist/* ``` -------------------------------- ### Help Emission Methods Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Methods for emitting different parts of the help message. ```APIDOC ## emit_help_epilogue(classes: bool) -> Generator[str, None, None] Yield the very bottom lines of the help message. If classes=False (the default), print –help-all msg. ## emit_options_help() -> Generator[str, None, None] Yield the lines for the options part of the help. ## emit_subcommands_help() -> Generator[str, None, None] Yield the lines for the subcommand part of the help. ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/ipython/traitlets/blob/main/docs/readme-docs.md Activates the created virtual environment. This command may vary depending on your operating system and shell. ```bash source activate ``` -------------------------------- ### Enable Argcomplete in Python Script Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Add this comment to the first 1024 bytes of a Python script to enable command-line tab completion for traitlets Applications when using argcomplete. ```python # PYTHON_ARGCOMPLETE_OK ``` -------------------------------- ### traitlets.config.SingletonConfigurable Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md A configurable that only allows one instance. Use the `instance()` method to create or retrieve the single instance. ```APIDOC ## class traitlets.config.SingletonConfigurable(*args: t.Any, **kwargs: t.Any) ### Description A configurable that only allows one instance. This class is for classes that should only have one instance of itself or *any* subclass. To create and retrieve such a class use the [`SingletonConfigurable.instance()`](#traitlets.config.SingletonConfigurable.instance) method. ### Class Methods #### clear_instance() Unset \_instance for this class and singleton parents. #### initialized() Check if an instance has been created. #### instance(*args: Any, **kwargs: Any) Returns a global instance of this class. This method creates a new instance if none have previously been created and returns a previously created instance if one already exists. The arguments and keyword arguments passed to this method are passed on to the `__init__()` method of the class upon instantiation. ### Examples Create a singleton class using instance, and retrieve it: ```default >>> from traitlets.config.configurable import SingletonConfigurable >>> class Foo(SingletonConfigurable): pass >>> foo = Foo.instance() >>> foo == Foo.instance() True ``` Create a subclass that is retrieved using the base class instance: ```default >>> class Bar(SingletonConfigurable): pass >>> class Bam(Bar): pass >>> bam = Bam.instance() >>> bam == Bar.instance() True ``` ``` -------------------------------- ### Using HasTraits Source: https://context7.com/ipython/traitlets/llms.txt Demonstrates how to create classes that inherit from HasTraits to define typed, observable attributes (traits). It shows instantiation with keyword arguments, type enforcement, and inspecting traits. ```APIDOC ## HasTraits — Base class for all trait-bearing objects Any class that needs typed, observable attributes must inherit from `HasTraits`. The metaclass `MetaHasTraits` automatically discovers all `TraitType` descriptors defined as class attributes, assigns their names, and registers default-value generators. Constructor keyword arguments that match known trait names are validated and applied atomically before notifications fire. ```python from traitlets import HasTraits, Int, Unicode, Float, Bool, List class Particle(HasTraits): name = Unicode("electron") charge = Float(-1.0) spin = Float(0.5) mass = Float(9.109e-31, help="Mass in kg") stable = Bool(True) tags = List() # Pass trait values as keyword args at construction time p = Particle(name="proton", charge=1.0, mass=1.673e-27) print(p.name) # proton print(p.charge) # 1.0 # Type enforcement try: p.charge = "positive" # raises TraitError except Exception as e: print(e) # The 'charge' trait of a Particle instance expected a float, not 'positive' # Inspect all traits on the class print(list(Particle.class_traits())) # ['charge', 'cross_validation_lock', 'mass', 'name', 'spin', 'stable', 'tags'] # Inspect trait values on an instance print(p.trait_values()) # {'name': 'proton', 'charge': 1.0, 'mass': 1.673e-27, 'spin': 0.5, 'stable': True, 'tags': []} ``` ``` -------------------------------- ### Config Object Methods Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Methods available on the Config object for managing configuration settings. ```APIDOC ## start_show_config() start function used when show_config is True ``` ```APIDOC ## traitlets.config.Config An attribute-based dict that can do smart merges. Accessing a field on a config object for the first time populates the key with either a nested Config object for keys starting with capitals or [`LazyConfigValue`](#traitlets.config.loader.LazyConfigValue) for lowercase keys, allowing quick assignments such as: ```default c = Config() c.Class.int_trait = 5 c.Class.list_trait.append("x") ``` ``` ```APIDOC ## collisions(other: [Config](#traitlets.config.Config)) Check for collisions between two config objects. Returns a dict of the form {“Class”: {“trait”: “collision message”}} indicating which values have been ignored. An empty dict indicates no collisions. ``` ```APIDOC ## copy() a shallow copy of D ``` ```APIDOC ## has_key(key: Any) True if the dictionary has the specified key, else False. ``` ```APIDOC ## merge(other: Any) merge another config object into this one ``` -------------------------------- ### traitlets.config.JSONFileConfigLoader Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md A JSON file loader for config. Can also act as a context manager that rewrites the configuration file to disk on exit. ```APIDOC ## class traitlets.config.JSONFileConfigLoader(filename: str, path: str | None = None, **kw: Any) ### Description A JSON file loader for config. Can also act as a context manager that rewrites the configuration file to disk on exit. ### Example ```default with JSONFileConfigLoader('myapp.json','/home/jupyter/configurations/') as c: c.MyNewConfigurable.new_value = 'Updated' ``` ### Methods #### load_config() Load the config from a file and return it as a Config object. ``` -------------------------------- ### traitlets.Dict.from_string_list Source: https://github.com/ipython/traitlets/blob/main/docs/source/trait_types.md Parses a list of configuration strings into a dictionary. Each string should be in the format 'key=value'. ```APIDOC ## from_string_list ### Description Return a dict from a list of config strings. This is where we parse CLI configuration. Each item should have the form "key=value". item parsing is done in [`item_from_string()`](#traitlets.Dict.item_from_string). ### Parameters - **s_list** (*list*[*str*]) – A list of strings, where each string is in the format "key=value". ``` -------------------------------- ### Common Arguments with Flags and Aliases Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Demonstrates using short (`-i`) and long (`--profile`) options for common arguments, which can be single characters or longer strings respectively. These are defined via `flags` and `aliases` attributes in `Application` subclasses. ```bash $ ipython -i -c "import numpy; x=numpy.linspace(0,1)" --profile testing --colors=lightbg ``` -------------------------------- ### traitlets.config.Configurable Source: https://github.com/ipython/traitlets/blob/main/docs/source/config-api.md Base class for configurable objects. Provides methods for generating configuration documentation and managing trait help. ```APIDOC ## class traitlets.config.Configurable(*args: t.Any, **kwargs: t.Any) ### Description Base class for configurable objects. Provides methods for generating configuration documentation and managing trait help. ### Class Methods #### class_config_rst_doc() Generate rST documentation for this class’ config options. Excludes traits defined on parent classes. #### class_config_section(classes: Sequence[type[[HasTraits](api.md#traitlets.HasTraits)]] | None = None) Get the config section for this class. Used to reduce redundant information. * **Parameters:** **classes** (*list* *,* *optional*) – The list of other classes in the config file. #### class_get_help(inst: [HasTraits](api.md#traitlets.HasTraits) | None = None) Get the help string for this class in ReST format. If inst is given, its current trait values will be used in place of class defaults. #### class_get_trait_help(trait: TraitType[Any, Any], inst: [HasTraits](api.md#traitlets.HasTraits) | None = None, helptext: str | None = None) Get the helptext string for a single trait. If not given, uses the help attribute of the current trait. * **Parameters:** * **inst** – If given, its current trait values will be used in place of the class default. * **helptext** – If not given, uses the help attribute of the current trait. #### class_print_help(inst: [HasTraits](api.md#traitlets.HasTraits) | None = None) Get the help string for a single trait and print it. #### section_names() Return section names as a list. ### Methods #### update_config(config: [Config](#traitlets.config.Config)) Update config and load the new values. ``` -------------------------------- ### Container traits with multiple arguments Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Illustrates the traitlets 5.0 approach for configuring container traits (List, Dict) by allowing the same key to be passed multiple times. This simplifies setting list items or dictionary key-value pairs from the command line. ```default myprogram -l a -l b ``` ```default myprogram -d a=5 -d b=10 ``` ```default ipython --ScriptMagics.script_paths='{"perl": "/usr/bin/perl"}' ``` ```default ipython \ --ScriptMagics.script_paths perl=/usr/bin/perl \ --ScriptMagics.script_paths ruby=/usr/local/opt/bin/ruby ``` -------------------------------- ### Define Configurable Classes with Inheritance Source: https://github.com/ipython/traitlets/blob/main/docs/source/config.md Define base and derived classes inheriting from `traitlets.config.Configurable`. Use `config=True` on traits to make them configurable. The configuration system respects the class inheritance hierarchy. ```python from traitlets.config import Application, Configurable from traitlets import Integer, Float, Unicode, Bool class Foo(Configurable): name = Unicode("fooname", config=True) value = Float(100.0, config=True) class Bar(Foo): name = Unicode("barname", config=True) othervalue = Int(0, config=True) # construct Bar(config=..) ```