Traitlets config API reference#
- class traitlets.config.Configurable(**kwargs: 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:
classes (list, 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(**kwargs: 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 instance(*args: Any, **kwargs: Any) CT #
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
- class traitlets.config.LoggingConfigurable(**kwargs: 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(**kwargs: 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_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_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 %(asctime)s
- 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 formatterconsole
.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"], }, }, }
- 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
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 #
- class traitlets.config.loader.LazyConfigValue(**kwargs: 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:
other (LazyConfigValue or container)
- Returns:
if
other
is also lazy, a reified container otherwise.- Return type:
- 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:
classes (optional, list) – The classes to scan for container config-traits and decide for their “multiplicity” when adding them as argparse arguments.
argv (optional, list) – If given, used to read command-line arguments from, otherwise sys.argv[1:] is used.
*parser_args (tuple) – A tuple of positional arguments that will be passed to the constructor of
argparse.ArgumentParser
.**parser_kw (dict) – A tuple of keyword arguments that will be passed to the constructor of
argparse.ArgumentParser
.aliases (dict of str to str) – Dict of aliases to full traitlets names for CLI parsing
flags (dict of str to str) – Dict of flags to full traitlets names for CLI parsing
log – Passed to ConfigLoader
- Returns:
config – The resulting Config object.
- Return type:
- load_config(argv: list[str] | None = None, aliases: ~typing.Any = None, flags: ~typing.Any = <Sentinel deprecated>, classes: ~typing.Any = None) Config #
Parse command line arguments and return as a Config object.
- Parameters:
argv (optional, 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.