Section#

class Section(**kwargs)#

Bases: HasTraits

Object holding configurable values.

This class inherits from traitlets.config.Configurable and so can hold configurable attributes as traits, 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.Instance trait, 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 aliases attribute. 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()).

Parameters:
  • config (abc.Mapping[str, t.Any] | None)

  • init_subsections (bool)

__contains__(key)#

Return if key leads to an existing subsection or trait.

Parameters:

key (str)

Return type:

bool

__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.

Parameters:

other (Any)

Return type:

bool

__getattr__(name)#

Patch for “did you mean” feature.

Parameters:

name (str)

__getitem__(key)#

Obtain value at key.

Parameters:

key (str)

Return type:

Any

__init__(config=None, *, init_subsections=True, **kwargs)#

Initialize section.

Parameters:
  • config (Mapping[str, Any] | None) – Flat dictionary containing values for the traits of this section, and its subsections. If a value is missing, the trait default value is used.

  • init_subsections (bool)

classmethod __init_subclass__(**kwargs)#

Call _setup_section().

__iter__()#

Iterate over possible keys.

Simply iter keys().

Return type:

Iterator[str]

__len__()#

Return number of valid keys.

Return type:

int

__ne__(other)#

Return self!=value.

Parameters:

other (Any)

Return type:

bool

__repr__()#

Return repr(self).

Return type:

str

__setitem__(key, value)#

Set a trait to a value.

Parameters:
  • key (str) – Path to leading to a trait.

  • value (Any)

__str__()#

Return str(self).

Return type:

str

_attr_completion_only_traits: bool = False#

Only keep configurable traits in attribute completion.

classmethod _class_subsections_recursive()#

Iterate recursively over all subsections.

Return type:

Iterator[type[Section]]

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

Generator[tuple[str, TraitType | type[Section]]]

classmethod _setup_section()#

Set up the class after definition.

This hook is run in __init_subclass__(), after any subclass of Section is 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 call traitlets.traitlets.HasTraits.setup_class() (cls.setup_class(cls.__dict__)).

Return type:

None

_subsections: dict[str, type[Section]] = {}#

Mapping of nested Section classes.

_subsections_recursive()#

Iterate recursively over all subsections.

Return type:

Iterator[Section]

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:

dict[str, Any]

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

copy(**kwargs)#

Return a copy.

Return type:

Self

classmethod defaults_recursive(nest=False, aliases=False, **metadata)#

Return nested dictionnary of default traits values.

Parameters:
Return type:

dict[str, Any]

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.

Return type:

list[str]

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.

Parameters:

fullpath (list[str] | None)

Return type:

list[str]

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.

Parameters:
  • fullpath (list[str])

  • trait (TraitType)

Return type:

list[str]

classmethod flatten_dict(nested)#

Flatten a dictionnary according to the structure of this section.

Parameters:

nested (Mapping[str, Any])

Return type:

dict[str, Any]

get(key, default=None)#

Obtain value at key.

Parameters:
  • key (str)

  • default (Any | None)

Return type:

Any

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.

Parameters:
Return type:

None

items(subsections=False, recursive=True, aliases=False)#

Return mapping of keys to values.

Keys can lead to subsections instances or trait values.

Parameters:
  • subsections (bool) – If True (default is False), keys can map to subsections instances.

  • 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.

Return type:

list[tuple[str, Any]]

keys(subsections=False, recursive=True, aliases=False)#

Return list of keys leading to subsections and traits.

Parameters:
  • subsections (bool) – If True (default is False), keys can lead to subsections instances.

  • recursive (bool) – If True (default), return keys for parameters from all subsections.

  • aliases (bool) – If True (default is False), include aliases.

Return type:

list[str]

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 priority is equal or higher.

Parameters:

configs (Mapping[str, ConfigValue])

Return type:

dict[str, ConfigValue]

classmethod nest_dict(flat)#

Nest a dictionnary according to the structure of this section.

Parameters:

flat (Mapping[str, Any])

Return type:

dict[str, Any]

pop(key, other=None)#

Sections do not support the pop operation.

A trait cannot be deleted.

Parameters:
  • key (str)

  • other (Any | None)

Return type:

Any

popitem()#

Sections do not support the popitem operation.

A trait cannot be deleted.

Return type:

tuple[str, Any]

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.

Parameters:

key (str | list[str]) – Dot separated (or a list of) attribute names that point to a trait in the configuration tree, starting from this Section. It might contain aliases/shortcuts.

Returns:

  • fullkey – Dot separated attribute names that unambiguously and uniquely point to a trait in the config tree, starting from this Section, ending with the trait name.

  • subsection – The Section class that contains the trait.

  • trait – The trait object corresponding to the key.

Return type:

tuple[str, type[Section], TraitType]

select(*keys, nest=False)#

Select parameters from this sections or its subsections.

Parameters:
  • keys (str) – Keys leading to parameters. To select parameters from subsections, use dot-separated syntax like "some.nested.parameter".

  • nest (bool) – If True return a nested dictionnary. Otherwise return a flat dictionnary with dot-separated keys. Default is False.

Return type:

dict[str, Any]

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.

Parameters:
  • key (str) – Path to leading to a trait.

  • default (TraitType | None) – Trait instance to add.

  • value (Any | Sentinel) – Value to set the new trait to if key does not lead to an existing trait. Can be left undefined if the trait has a default value.

Return type:

Any

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 to functools.partial() objects.

  • trait_select (Mapping | None) – Passed to trait_names(). Restrict to traits validating those conditions. Default is dict(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:

dict

classmethod traits_recursive(nest=False, aliases=False, **metadata)#

Return dictionnary of all traits.

Parameters:
Return type:

dict[str, TraitType]

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.

values(subsections=False, recursive=True, aliases=False)#

List of subsections instances and trait values.

In the same order as keys().

Parameters:
  • subsections (bool) – If True (default is False), values include subsections instances.

  • recursive (bool) – If True (default), return all subsections.

  • aliases (bool) – If True (default is False), include aliases.

Return type:

list[Any]