Traitlets config API reference#

class traitlets.config.Configurable(*args: t.Any, **kwargs: t.Any)#
classmethod class_config_rst_doc() str#

Generate rST documentation for this class’ config options.

Excludes traits defined on parent classes.

classmethod class_config_section(classes: Sequence[type[HasTraits]] | None = None) str#

Get the config section for this class.

Parameters:
classeslist, optional

The list of other classes in the config file. Used to reduce redundant information.

classmethod class_get_help(inst: HasTraits | None = None) str#

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.

classmethod class_get_trait_help(trait: TraitType[Any, Any], inst: HasTraits | None = None, helptext: str | None = None) str#

Get the helptext string for a single 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.

classmethod class_print_help(inst: HasTraits | None = None) None#

Get the help string for a single trait and print it.

classmethod section_names() list[str]#

return section names as a list

update_config(config: Config) None#

Update config and load the new values

class traitlets.config.SingletonConfigurable(*args: t.Any, **kwargs: t.Any)#

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() method.

classmethod clear_instance() None#

unset _instance for this class and singleton parents.

Changed in version 5.17: Inside an active SingletonScope, clears the scope’s registry instead, leaving the process-global _instance alone.

classmethod initialized() bool#

Has an instance been created?

Changed in version 5.17: Inside an active SingletonScope, reports whether an instance exists in that scope, ignoring the process-global one.

classmethod instance(*args: t.Any, **kwargs: t.Any) Self#

Returns a global instance of this class.

This method create a new instance if none have previously been created and returns a previously created instance is 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:

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

>>> class Bar(SingletonConfigurable): pass
>>> class Bam(Bar): pass
>>> bam = Bam.instance()
>>> bam == Bar.instance()
True

Changed in version 5.17: Inside an active SingletonScope, resolves against that scope’s registry — creating a fresh instance on first use — without reading, creating, or mutating the process-global _instance.

classmethod scope() SingletonScope#

Create a scope covering this class and its subclasses.

The returned SingletonScope is not active yet; call it to activate it for a dynamic extent (with MyApp.scope()() as scope:, or bind it first to inspect or re-enter it later). Called on SingletonConfigurable itself, it covers every singleton in the process.

Added in version 5.17.

class traitlets.config.SingletonScope(base: type[SingletonConfigurable])#

An isolated singleton registry, activated for a dynamic extent.

While active (with scope():), SingletonConfigurable.instance() on any subclass of base resolves within this registry — creating fresh instances on first use — in the current thread/async task. Re-enterable: the registry persists across activations.

Warning

The scope lives in a ContextVar. On builds where sys.flags.thread_inherit_context is enabled — the default on the free-threaded build (e.g. 3.14t) — a threading.Thread started while the scope is active inherits a copy of the parent context and resolves .instance() within the scope instead of the process-global registry. Activating a scope under that flag emits a RuntimeWarning. For per-thread isolation, activate a fresh scope inside each thread rather than relying on non-inheritance.

Scope SingletonConfigurable itself for a complete blank slate covering every singleton in the process.

Added in version 5.17.

add(inst: SingletonConfigurable) None#

Pre-seed the registry with an instance you built yourself, so that .instance() returns that object inside the scope.

Writes through to the singleton parents of type(inst), the same way the classic global path does, so a subclass instance is also returned when resolving via an ancestor class. This is the only way to control which object in-scope .instance() calls receive, since they otherwise construct a fresh one.

Added in version 5.17.

covers(cls: type) bool#

Whether cls resolves within this scope.

Added in version 5.17.

get(cls: type[CT]) CT | None#

Registered instance for cls, emulating class-attribute inheritance: walk cls.__mro__ and return the first hit.

Added in version 5.17.

class traitlets.config.LoggingConfigurable(*args: t.Any, **kwargs: t.Any)#

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.

log#

Logger or LoggerAdapter instance

class traitlets.config.JSONFileConfigLoader(filename: str, path: str | None = None, **kw: Any)#

A JSON file loader for config

Can also act as a context manager that rewrite the configuration file to disk on exit.

Example:

with JSONFileConfigLoader('myapp.json','/home/jupyter/configurations/') as c:
    c.MyNewConfigurable.new_value = 'Updated'
load_config() Config#

Load the config from a file and return it as a Config object.

class traitlets.config.Application(*args: t.Any, **kwargs: t.Any)#

A singleton application with full configuration support.

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.

document_config_options() str#

Generate rST format documentation for the config options this application

Returns a multiline string.

emit_alias_help() Generator[str, None, None]#

Yield the lines for alias part of the help.

emit_description() Generator[str, None, None]#

Yield lines with the application description.

emit_examples() Generator[str, None, None]#

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() Generator[str, None, None]#

Yield the lines for the flag part of the help.

emit_help(classes: bool = False) Generator[str, None, None]#

Yield the help-lines for each Configurable class in self.classes.

If classes=False (the default), only flags and aliases are printed.

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.

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]] | None = None) str#

generate default config file from Configurables

get_default_logging_config() dict[str, Any]#

Return the base logging configuration.

The default is to log to stderr using a StreamHandler, if no default handler already exists.

The log handler level starts at logging.WARN, but this can be adjusted by setting the log_level attribute.

The logging_config trait is merged into this allowing for finer control of logging.

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.

json_config_loader_class#

alias of JSONFileConfigLoader

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

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.

property loaded_config_files: list[str]#

Currently loaded configuration files

log_datefmt#

The date format used by logging formatters for logging.Formatter datefmt parameter

log_format#

The Logging format template

log_level#

Set the log level by value or name.

logging_config#

Configure additional log handlers.

The default stderr logs handler is configured by the log_level, log_datefmt and log_format settings.

This configuration can be used to configure additional handlers (e.g. to output the log to a file) or for finer control over the default handlers.

If provided this should be a logging configuration dictionary, for more information see: https://docs.python.org/3/library/logging.config.html#logging-config-dictschema

This dictionary is merged with the base logging configuration which defines the following:

  • A logging formatter intended for interactive use called console.

  • A logging handler that writes to stderr called console which uses the formatter console.

  • A logger with the name of this application set to DEBUG level.

This example adds a new handler that writes to a file:

c.Application.logging_config = {
    "handlers": {
        "file": {
            "class": "logging.FileHandler",
            "level": "DEBUG",
            "filename": "<path/to/file>",
        }
    },
    "loggers": {
        "<application-name>": {
            "level": "DEBUG",
            # NOTE: if you don't list the default "console"
            # handler here then it will be disabled
            "handlers": ["console", "file"],
        },
    },
}
parse_command_line(argv: list[str] | None = None) None#

Parse the command line arguments.

print_alias_help() None#

Print the alias parts of the help.

print_description() None#

Print the application description.

print_examples() None#

Print usage and examples (see emit_examples()).

print_flag_help() None#

Print the flag part of the help.

print_help(classes: bool = False) None#

Print the help for each Configurable class in self.classes.

If classes=False (the default), only flags and aliases are printed.

print_options() None#

Print the options part of the help.

print_subcommands() None#

Print the subcommand part of the help.

print_version() None#

Print the version string.

python_config_loader_class#

alias of PyFileConfigLoader

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)

start() None#

Start the app mainloop.

Override in subclasses.

start_show_config() None#

start function used when show_config is True

class traitlets.config.Config(*args: Any, **kwds: Any)#

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 for lowercase keys, allowing quick assignments such as:

c = Config()
c.Class.int_trait = 5
c.Class.list_trait.append("x")
collisions(other: Config) dict[str, Any]#

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.

copy() a shallow copy of D#
has_key(key: Any) bool#

True if the dictionary has the specified key, else False.

merge(other: Any) None#

merge another config object into this one

class traitlets.config.loader.LazyConfigValue(*args: t.Any, **kwargs: t.Any)#

Proxy object for exposing methods on configurable containers

These methods allow appending/extending/updating to add to non-empty defaults instead of clobbering them.

Exposes:

  • append, extend, insert on lists

  • update on dicts

  • update, add on sets

add(obj: Any) None#

Add an item to a set

append(obj: Any) None#

Append an item to a List

extend(other: Any) None#

Extend a list

get_value(initial: Any) Any#

construct the value from the initial one

after applying any insert / extend / update changes

merge_into(other: Any) Any#

Merge with another earlier LazyConfigValue or an earlier container. This is useful when having global system-wide configuration files.

Self is expected to have higher precedence.

Parameters:
otherLazyConfigValue or container
Returns:
LazyConfigValue

if other is also lazy, a reified container otherwise.

prepend(other: Any) None#

like list.extend, but for the front

to_dict() dict[str, Any]#

return JSONable dict form of my data

Currently update as dict or set, extend, prepend as lists, and inserts as list of tuples.

update(other: Any) None#

Update either a set or dict

class traitlets.config.loader.KVArgParseConfigLoader(argv: list[str] | None = None, aliases: dict[str, str] | None = None, flags: dict[str, str] | None = None, log: Any = None, classes: list[type[Any]] | None = None, subcommands: dict[str, Any] | None = None, *parser_args: Any, **parser_kw: Any)#

A config loader that loads aliases and flags with argparse,

as well as arbitrary –Class.trait value

__init__(argv: list[str] | None = None, aliases: dict[str, str] | None = None, flags: dict[str, str] | None = None, log: Any = None, classes: list[type[Any]] | None = None, subcommands: dict[str, Any] | None = None, *parser_args: Any, **parser_kw: Any) None#

Create a config loader for use with argparse.

Parameters:
classesoptional, list

The classes to scan for container config-traits and decide for their “multiplicity” when adding them as argparse arguments.

argvoptional, list

If given, used to read command-line arguments from, otherwise sys.argv[1:] is used.

*parser_argstuple

A tuple of positional arguments that will be passed to the constructor of argparse.ArgumentParser.

**parser_kwdict

A tuple of keyword arguments that will be passed to the constructor of argparse.ArgumentParser.

aliasesdict of str to str

Dict of aliases to full traitlets names for CLI parsing

flagsdict of str to str

Dict of flags to full traitlets names for CLI parsing

log

Passed to ConfigLoader

load_config(argv: list[str] | None = None, aliases: Any = None, flags: Any = <Sentinel deprecated>, classes: Any = None) Config#

Parse command line arguments and return as a Config object.

Parameters:
argvoptional, list

If given, a list with the structure of sys.argv[1:] to parse arguments from. If not given, the instance’s self.argv attribute (given at construction time) is used.

flags

Deprecated in traitlets 5.0, instantiate the config loader with the flags.