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.
- 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_instancealone.
- 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
SingletonScopeis 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 onSingletonConfigurableitself, 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 ofbaseresolves 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 wheresys.flags.thread_inherit_contextis enabled — the default on the free-threaded build (e.g.3.14t) — athreading.Threadstarted 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 aRuntimeWarning. For per-thread isolation, activate a fresh scope inside each thread rather than relying on non-inheritance.Scope
SingletonConfigurableitself 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.
- 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'
- 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_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_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_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 notkey: (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_levelattribute.The
logging_configtrait 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_file(filename: str, path: str | Sequence[str | None] | None = None) None#
Load config files by filename and path.
- log_datefmt#
The date format used by logging formatters for logging.Formatter
datefmtparameter
- 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
consolewhich uses the formatterconsole.A logger with the name of this application set to
DEBUGlevel.
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"], }, }, }
- 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.
- 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)
- 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
LazyConfigValuefor 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#
- 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
- 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
otheris also lazy, a reified container otherwise.
- 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.