Section#
- class Section(**kwargs)#
Bases:
HasTraitsObject holding configurable values.
This class inherits from
traitlets.config.Configurableand so can hold configurable attributes astraits, but also expands to allow nested configuration. Other Section classes can be set as attribute in order to specify parameters in deeper nested levels.The main features of this class are:
all traits are automatically tagged as configurable (
.tag(config=True)), unless already tagged.Any class attribute that is a subclass of Section will be registered as a nested subsection and replaced by a
traitlets.Instancetrait, tagged as a “subsection” in its metadata.Any nested class definition (subclass of Section) will also be considered as a subsection whose name is that of the class. The class definition will be kept under another attribute name (
_{subsection}SectionDef).Shortcuts to nested subsections can be defined in the
aliasesattribute. This allows to specify shorter keys (in command line or config files).
The API expand to recursively retrieve all traits (or their values) from this section and its subsections. It defines help emitting functions, suitable for command line help message. It also enables having unique keys that point to a specific trait in the configuration tree (see
resolve_key()).- __contains__(key)#
Return if key leads to an existing subsection or trait.
- __dir__()#
Default dir() implementation.
- __eq__(other)#
Check equality with other section.
If other is not a Section, will return False. Both section must have the same keys and same values.
- __init__(config=None, *, init_subsections=True, **kwargs)#
Initialize section.
- classmethod __init_subclass__(**kwargs)#
Call
_setup_section().
- __setitem__(key, value)#
Set a trait to a value.
- classmethod _class_subsections_recursive()#
Iterate recursively over all subsections.
- _dynamic_subsections = True#
Allow dynamic definition of subsections.
Any attribute that is a Section will be converted to a trait instance and added to the subsections. Class definitions will be modified appropriately.
- classmethod _iter_traits(subsections: Literal[False], recursive: bool = True, aliases: bool = False, own_traits: bool = False, **metadata) Generator[tuple[str, TraitType]]#
- classmethod _iter_traits(subsections: bool = False, recursive: bool = True, aliases: bool = False, own_traits: bool = False, **metadata) Generator[tuple[str, TraitType | type[Section]]]
Iterate over keys and traits.
Traits are identical for class and instances. This method is thus used by class_traits_recursive, traits_recursive and keys.
- Parameters:
subsections (bool) – If True (default is False), keys can map to subsections classes.
recursive (bool) – If True (default), return parameters from all subsections. Otherwise limit to only this section.
aliases (bool) – If True (default is False), include aliases.
own_traits (bool) – If True do not list traits from parent classes. Default to False.
- Return type:
- classmethod _setup_section()#
Set up the class after definition.
This hook is run in
__init_subclass__(), after any subclass ofSectionis defined.This method can be modified by subclasses in need of specific behavior. Do not forget to call the
super()version, and if traits are added/modified it might be necessary to calltraitlets.traitlets.HasTraits.setup_class()(cls.setup_class(cls.__dict__)).- Return type:
None
- add_trait(key, trait, allow_recursive=True)#
Add a trait to this section or one of its subsection.
The trait name cannot be already in use.
- Parameters:
key (str) – Path of dot separated attribute names leading to the trait to add. It can also only be a trait name to add to this section.
trait (TraitType) – Trait instance to add.
allow_recursive (bool) – If True (default), subsections specified in key that are not contained in this section will be added automatically. Otherwise, this will raise on unknown subsections in key.
- aliases: dict[str, str] = {}#
Mapping of aliases/shortcuts.
The shortcut name maps to the subsection it points to, for example:
{“short”: “some.deeply.nested.subsection”}
will allow to specify parameters in two equivalent ways:
some.deeply.nested.subsection.my_parameter = 2 short.my_parameter = 2
- as_dict(recursive=True, aliases=False, nest=False)#
Return traits as a dictionary.
- Parameters:
recursive (bool) – If True (default), return parameters from all subsections. Otherwise limit to only this section.
aliases (bool) – If True, include aliases. Default is False.
nest (bool) – If True return a nested dictionnary. Otherwise return a flat dictionnary with dot-separated keys. Default is False.
- Return type:
- clear()#
Sections do not support the clear operation.
A trait cannot be deleted. You may use
reset()to reset all traits to their default value.- Return type:
None
- classmethod defaults_recursive(nest=False, aliases=False, **metadata)#
Return nested dictionnary of default traits values.
- classmethod emit_description()#
Return lines of description of this section.
Take the section docstring if defined, and format it nicely (wraps it, remove trailing whitespace, etc.). Return a list of lines.
- classmethod emit_help(fullpath=None)#
Return help for this section, and its subsections recursively.
Contains the name of this section, its description if it has one, eventual aliases/shortcuts, help on each trait, and same thing recursively on subsections.
Format the help so that it can be used as help for specifying values from the command line.
- classmethod emit_trait_help(fullpath, trait)#
Return lines of help for a trait of this section.
Format the help so that it can be used as help for specifying values from the command line.
- classmethod flatten_dict(nested)#
Flatten a dictionnary according to the structure of this section.
- get(key, default=None)#
Obtain value at key.
- classmethod help()#
Print description of this section and its traits.
- Return type:
None
- import_types(allow_error=True, recursive=True, **metadata)#
Transform Type traits with string value into a type object.
Only works for simple Type traits and if in Unions.
- items(subsections=False, recursive=True, aliases=False)#
Return mapping of keys to values.
Keys can lead to subsections instances or trait values.
- Parameters:
- Return type:
- keys(subsections=False, recursive=True, aliases=False)#
Return list of keys leading to subsections and traits.
- static merge_configs(*configs)#
Merge multiple flat configuration mappings.
If there is a conflict between values, configurations specified later in the argument list will take priority (ie last one wins). The value from the precedent config is replaced if the
value's priorityis equal or higher.- Parameters:
configs (Mapping[str, ConfigValue])
- Return type:
- classmethod nest_dict(flat)#
Nest a dictionnary according to the structure of this section.
- pop(key, other=None)#
Sections do not support the pop operation.
A trait cannot be deleted.
- popitem()#
Sections do not support the popitem operation.
A trait cannot be deleted.
- postinit()#
Run any instructions after instantiation.
This allows to set/modify traits depending on other traits values.
- reset()#
Reset all traits to their default value.
- Return type:
None
- classmethod resolve_key(key)#
Resolve a key.
- select(*keys, nest=False)#
Select parameters from this sections or its subsections.
- Parameters:
- Return type:
- setdefault(key, default=None, value=traitlets.Undefined)#
Set a trait to a value if it exists.
If the trait exists, return its value. Otherwise, the default argument must be provide a trait instance to add it to the section, it is set to value if it is provided as well.
- trait_values_from_func_signature(func, trait_select=None, **kwargs)#
Return trait values that appear in a function signature.
Only consider the function arguments that can supplied as a keyword argument, and whose name is that of a configurable trait. A trait without value (specified or default) will be ignored. Unbound arguments (ie
**kwargs) are ignored.- Parameters:
func (Callable) – The callable to guess parameters from. Parameters are retrieved using
inspect.signature(). From its documentation: Accepts a wide range of callables: from plain functions and classes tofunctools.partial()objects.trait_select (Mapping | None) – Passed to
trait_names(). Restrict to traits validating those conditions. Default isdict(config=True).kwargs – Passed to
inspect.signature().
- Returns:
params – A mapping of parameters names to their values. Can be passed directly to
func.- Return type:
- classmethod traits_recursive(nest=False, aliases=False, **metadata)#
Return dictionnary of all traits.
- update(other=None, allow_new=False, raise_on_miss=False, **kwargs)#
Update values of this Section traits.
This does not block trait notification. This must be done manually for all the relevant sections.
- Parameters:
other (Section | Mapping[str, Any] | None) – Other Section to take traits values from (recursively). It can also be a flat mapping of full path keys (
"some.path.to.trait") to values or trait instances, which default value will be used.allow_new (bool) – If True, allow creating new traits for this Section. If other is a section the trait is copied over; in a mapping it must be a trait instance which default value will be used. Default is False.
raise_on_miss (bool) – If True, raise an exception if a trait in other is placed on a path that does not lead to an existing subsection or trait. Default is False.
kwargs – Same as other.