Traitlets config API reference#
- class traitlets.config.Configurable(**kwargs: Any)#
- classmethod class_config_rst_doc()#
Generate rST documentation for this class’ config options.
Excludes traits defined on parent classes.
- classmethod class_config_section(classes=None)#
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=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.
- classmethod class_get_trait_help(trait, inst=None, helptext=None)#
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=None)#
Get the help string for a single trait and print it.
- classmethod section_names()#
return section names as a list
- update_config(config)#
Update config and load the new values
- 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 clear_instance()#
unset _instance for this class and singleton parents.
- classmethod initialized()#
Has an instance been created?
- classmethod instance(*args, **kwargs)#
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 retrived 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, path=None, **kw)#
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()#
Load the config from a file and return it as a Config object.
- class traitlets.config.Application(**kwargs: Any)#
A singleton application with full configuration support.
- 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=False)#
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)#
Yield the very bottom lines of the help message.
If classes=False (the default), print –help-all msg.
- emit_options_help()#
Yield the lines for the options part of the help.
- emit_subcommands_help()#
Yield the lines for the subcommand part of the help.
- flatten_flags()#
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=None)#
generate default config file from Configurables
- get_default_logging_config()#
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=None)#
Do the basic steps to configure me.
Override in subclasses.
- initialize_subcommand(subc, argv=None)#
Initialize a subcommand with argv.
- json_config_loader_class#
alias of
JSONFileConfigLoader
- classmethod launch_instance(argv=None, **kwargs)#
Launch a global instance of this Application
If a global instance already exists, this reinitializes and starts it
- load_config_file(filename, path=None)#
Load config files by filename and path.
- property loaded_config_files#
Currently loaded configuration files
- log_datefmt: str | Unicode[str, str | bytes]#
The date format used by logging formatters for %(asctime)s
- parse_command_line(argv=None)#
Parse the command line arguments.
- print_alias_help()#
Print the alias parts of the help.
- print_description()#
Print the application description.
- print_examples()#
Print usage and examples (see emit_examples()).
- print_flag_help()#
Print the flag part of the help.
- print_help(classes=False)#
Print the help for each Configurable class in self.classes.
If classes=False (the default), only flags and aliases are printed.
- print_options()#
Print the options part of the help.
- print_subcommands()#
Print the subcommand part of the help.
- print_version()#
Print the version string.
- python_config_loader_class#
alias of
PyFileConfigLoader
- show_config: bool | Bool[bool, bool | int]#
Instead of starting the Application, dump configuration to stdout
- show_config_json: bool | Bool[bool, bool | int]#
Instead of starting the Application, dump configuration to stdout (as JSON)
- start()#
Start the app mainloop.
Override in subclasses.
- start_show_config()#
start function used when show_config is True
- class traitlets.config.Config(*args, **kwds)#
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)#
True if the dictionary has the specified key, else False.
- merge(other)#
merge another config object into this one
- 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
- add(obj)#
Add an item to a set
- append(obj)#
Append an item to a List
- extend(other)#
Extend a list
- get_value(initial)#
construct the value from the initial one
after applying any insert / extend / update changes
- merge_into(other)#
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:
- prepend(other)#
like list.extend, but for the front
- to_dict()#
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)#
Update either a set or dict
- class traitlets.config.loader.KVArgParseConfigLoader(argv: List[str] | None = None, aliases: Dict[str | Tuple[str, ...], str] | None = None, flags: Dict[str | Tuple[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 | Tuple[str, ...], str] | None = None, flags: Dict[str | Tuple[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=None, aliases=None, flags=<Sentinel deprecated>, classes=None)#
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, instanciate the config loader with the flags.