Trait Types#

class traitlets.TraitType#

The base class for all trait types.

__init__(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: Any = None, **kwargs: Any) None#

Declare a traitlet.

If allow_none is True, None is a valid value in addition to any values that are normally valid. The default is up to the subclass. For most trait types, the default value for allow_none is False.

If read_only is True, attempts to directly modify a trait attribute raises a TraitError.

If help is a string, it documents the attribute’s purpose.

Extra metadata can be associated with the traitlet using the .tag() convenience method or by using the traitlet instance’s .metadata dictionary.

from_string(s: str) G | None#

Get a value from a config string

such as an environment variable or CLI arguments.

Traits can override this method to define their own parsing of config strings.

See also

item_from_string

Added in version 5.0.

Numbers#

traitlets.Integer#

alias of Int

class traitlets.Int#
class traitlets.Long#

On Python 2, these are traitlets for values where the int and long types are not interchangeable. On Python 3, they are both aliases for Integer.

In almost all situations, you should use Integer instead of these.

class traitlets.Float(default_value: float | Sentinel = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)#
class traitlets.Float(default_value: float | Sentinel | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)

A float trait.

class traitlets.Complex(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: Any = None, **kwargs: Any)#

A trait for complex numbers.

class traitlets.CInt#
class traitlets.CLong#
class traitlets.CFloat#
class traitlets.CComplex#

Casting variants of the above. When a value is assigned to the attribute, these will attempt to convert it by calling e.g. value = int(value).

Strings#

class traitlets.Unicode(default_value: str | Sentinel = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any = ..., **kwargs: Any)#
class traitlets.Unicode(default_value: str | Sentinel | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any = ..., **kwargs: Any)

A trait for unicode strings.

class traitlets.Bytes(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: Any = None, **kwargs: Any)#

A trait for byte strings.

class traitlets.CUnicode#
class traitlets.CBytes#

Casting variants. When a value is assigned to the attribute, these will attempt to convert it to their type. They will not automatically encode/decode between unicode and bytes, however.

class traitlets.ObjectName(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: Any = None, **kwargs: Any)#

A string holding a valid object name in this version of Python.

This does not check that the name exists in any scope.

class traitlets.DottedObjectName(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: Any = None, **kwargs: Any)#

A string holding a valid dotted object name in Python, such as A.b3._c

Containers#

class traitlets.List(trait: List[T] | Tuple[T] | Set[T] | Sentinel | TraitType[T, Any] | None = None, default_value: List[T] | Tuple[T] | Set[T] | Sentinel | None = traitlets.Undefined, minlen: int = 0, maxlen: int = 9223372036854775807, **kwargs: Any)#

An instance of a Python list.

__init__(trait: List[T] | Tuple[T] | Set[T] | Sentinel | TraitType[T, Any] | None = None, default_value: List[T] | Tuple[T] | Set[T] | Sentinel | None = traitlets.Undefined, minlen: int = 0, maxlen: int = 9223372036854775807, **kwargs: Any) None#

Create a List trait type from a list, set, or tuple.

The default value is created by doing list(default_value), which creates a copy of the default_value.

trait can be specified, which restricts the type of elements in the container to that TraitType.

If only one arg is given and it is not a Trait, it is taken as default_value:

c = List([1, 2, 3])

Parameters:
  • trait (TraitType [ optional ]) – the type for restricting the contents of the Container. If unspecified, types are not checked.

  • default_value (SequenceType [ optional ]) – The default value for the Trait. Must be list/tuple/set, and will be cast to the container type.

  • minlen (Int [ default 0 ]) – The minimum length of the input list

  • maxlen (Int [ default sys.maxsize ]) – The maximum length of the input list

from_string_list(s_list: list[str]) T | None#

Return the value from a list of config strings

This is where we parse CLI configuration

item_from_string(s: str, index: int | None = None) T | str#

Cast a single item from a string

Evaluated when parsing CLI configuration from a string

class traitlets.Set(trait: Any = None, default_value: Any = traitlets.Undefined, minlen: int = 0, maxlen: int = 9223372036854775807, **kwargs: Any)#

An instance of a Python set.

__init__(trait: Any = None, default_value: Any = traitlets.Undefined, minlen: int = 0, maxlen: int = 9223372036854775807, **kwargs: Any) None#

Create a Set trait type from a list, set, or tuple.

The default value is created by doing set(default_value), which creates a copy of the default_value.

trait can be specified, which restricts the type of elements in the container to that TraitType.

If only one arg is given and it is not a Trait, it is taken as default_value:

c = Set({1, 2, 3})

Parameters:
  • trait (TraitType [ optional ]) – the type for restricting the contents of the Container. If unspecified, types are not checked.

  • default_value (SequenceType [ optional ]) – The default value for the Trait. Must be list/tuple/set, and will be cast to the container type.

  • minlen (Int [ default 0 ]) – The minimum length of the input list

  • maxlen (Int [ default sys.maxsize ]) – The maximum length of the input list

class traitlets.Tuple(*traits: Any, **kwargs: Any)#

An instance of a Python tuple.

__init__(*traits: Any, **kwargs: Any) None#

Create a tuple from a list, set, or tuple.

Create a fixed-type tuple with Traits:

t = Tuple(Int(), Str(), CStr())

would be length 3, with Int,Str,CStr for each element.

If only one arg is given and it is not a Trait, it is taken as default_value:

t = Tuple((1, 2, 3))

Otherwise, default_value must be specified by keyword.

Parameters:
  • *traits (TraitTypes [ optional ]) – the types for restricting the contents of the Tuple. If unspecified, types are not checked. If specified, then each positional argument corresponds to an element of the tuple. Tuples defined with traits are of fixed length.

  • default_value (SequenceType [ optional ]) – The default value for the Tuple. Must be list/tuple/set, and will be cast to a tuple. If traits are specified, default_value must conform to the shape and type they specify.

  • **kwargs – Other kwargs passed to Container

class traitlets.Dict(value_trait: TraitType[t.Any, t.Any] | dict[K, V] | Sentinel | None = None, per_key_traits: t.Any = None, key_trait: TraitType[t.Any, t.Any] | None = None, default_value: dict[K, V] | Sentinel | None = traitlets.Undefined, **kwargs: t.Any)#

An instance of a Python dict.

One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

Changed in version 5.0: Added key_trait for validating dict keys.

Changed in version 5.0: Deprecated ambiguous trait, traits args in favor of value_trait, per_key_traits.

__init__(value_trait: TraitType[t.Any, t.Any] | dict[K, V] | Sentinel | None = None, per_key_traits: t.Any = None, key_trait: TraitType[t.Any, t.Any] | None = None, default_value: dict[K, V] | Sentinel | None = traitlets.Undefined, **kwargs: t.Any) None#

Create a dict trait type from a Python dict.

The default value is created by doing dict(default_value), which creates a copy of the default_value.

Parameters:
  • value_trait (TraitType [ optional ]) – The specified trait type to check and use to restrict the values of the dict. If unspecified, values are not checked.

  • per_key_traits (Dictionary of {keys:trait types} [ optional, keyword-only ]) – A Python dictionary containing the types that are valid for restricting the values of the dict on a per-key basis. Each value in this dict should be a Trait for validating

  • key_trait (TraitType [ optional, keyword-only ]) – The type for restricting the keys of the dict. If unspecified, the types of the keys are not checked.

  • default_value (SequenceType [ optional, keyword-only ]) – The default value for the Dict. Must be dict, tuple, or None, and will be cast to a dict if not None. If any key or value traits are specified, the default_value must conform to the constraints.

Examples

a dict whose values must be text >>> d = Dict(Unicode())

d2[‘n’] must be an integer d2[‘s’] must be text >>> d2 = Dict(per_key_traits={“n”: Integer(), “s”: Unicode()})

d3’s keys must be text d3’s values must be integers >>> d3 = Dict(value_trait=Integer(), key_trait=Unicode())

from_string_list(s_list: list[str]) Any#

Return a dict from a list of config strings.

This is where we parse CLI configuration.

Each item should have the form "key=value".

item parsing is done in item_from_string().

item_from_string(s: str) dict[K, V]#

Cast a single-key dict from a string.

Evaluated when parsing CLI configuration from a string.

Dicts expect strings of the form key=value.

Returns a one-key dictionary, which will be merged in from_string_list().

Classes and instances#

class traitlets.Instance(klass: type[T] = ..., args: tuple[Any, ...] | None = ..., kw: dict[str, Any] | None = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: Any)#
class traitlets.Instance(klass: type[T] = ..., args: tuple[Any, ...] | None = ..., kw: dict[str, Any] | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: Any)
class traitlets.Instance(klass: str | None = ..., args: tuple[Any, ...] | None = ..., kw: dict[str, Any] | None = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: Any)
class traitlets.Instance(klass: str | None = ..., args: tuple[Any, ...] | None = ..., kw: dict[str, Any] | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: Any)

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

__init__(klass: type[T] = None, args: tuple[Any, ...] | None = None, kw: dict[str, Any] | None = None, allow_none: Literal[False] = False, read_only: bool | None = None, help: str | None = None, **kwargs: Any) None#
__init__(klass: type[T] = None, args: tuple[Any, ...] | None = None, kw: dict[str, Any] | None = None, allow_none: Literal[True] = False, read_only: bool | None = None, help: str | None = None, **kwargs: Any) None
__init__(klass: str | None = None, args: tuple[Any, ...] | None = None, kw: dict[str, Any] | None = None, allow_none: Literal[False] = False, read_only: bool | None = None, help: str | None = None, **kwargs: Any) None
__init__(klass: str | None = None, args: tuple[Any, ...] | None = None, kw: dict[str, Any] | None = None, allow_none: Literal[True] = False, read_only: bool | None = None, help: str | None = None, **kwargs: Any) None

Construct an Instance trait.

This trait allows values that are instances of a particular class or its subclasses. Our implementation is quite different from that of enthough.traits as we don’t allow instances to be used for klass and we handle the args and kw arguments differently.

Parameters:
  • klass (class, str) – The class that forms the basis for the trait. Class names can also be specified as strings, like ‘foo.bar.Bar’.

  • args (tuple) – Positional arguments for generating the default value.

  • kw (dict) – Keyword arguments for generating the default value.

  • allow_none (bool [ default False ]) – Indicates whether None is allowed as a value.

  • **kwargs – Extra kwargs passed to ClassBasedTraitType

Notes

If both args and kw are None, then the default value is None. If args is a tuple and kw is a dict, then the default is created as klass(*args, **kw). If exactly one of args or kw is None, the None is replaced by () or {}, respectively.

class traitlets.Type(default_value: Sentinel | None | str = ..., klass: None | str = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)#
class traitlets.Type(default_value: Sentinel | None | str = ..., klass: None | str = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)
class traitlets.Type(default_value: S = ..., klass: S = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)
class traitlets.Type(default_value: S | None = ..., klass: S = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)

A trait whose value must be a subclass of a specified class.

__init__(default_value: Sentinel | None | str = traitlets.Undefined, klass: None | str = None, allow_none: Literal[False] = False, read_only: bool | None = None, help: str | None = None, config: Any | None = None, **kwargs: Any) None#
__init__(default_value: Sentinel | None | str = traitlets.Undefined, klass: None | str = None, allow_none: Literal[True] = False, read_only: bool | None = None, help: str | None = None, config: Any | None = None, **kwargs: Any) None
__init__(default_value: S = traitlets.Undefined, klass: S = None, allow_none: Literal[False] = False, read_only: bool | None = None, help: str | None = None, config: Any | None = None, **kwargs: Any) None
__init__(default_value: S | None = traitlets.Undefined, klass: S = None, allow_none: Literal[True] = False, read_only: bool | None = None, help: str | None = None, config: Any | None = None, **kwargs: Any) None

Construct a Type trait

A Type trait specifies that its values must be subclasses of a particular class.

If only default_value is given, it is used for the klass as well. If neither are given, both default to object.

Parameters:
  • default_value (class, str or None) – The default value must be a subclass of klass. If an str, the str must be a fully specified class name, like ‘foo.bar.Bah’. The string is resolved into real class, when the parent HasTraits class is instantiated.

  • klass (class, str [ default object ]) – Values of this trait must be a subclass of klass. The klass may be specified in a string like: ‘foo.bar.MyClass’. The string is resolved into real class, when the parent HasTraits class is instantiated.

  • allow_none (bool [ default False ]) – Indicates whether None is allowed as an assignable value.

  • **kwargs – extra kwargs passed to ClassBasedTraitType

class traitlets.This(**kwargs: Any)#

A trait for instances of the class containing this trait.

Because how how and when class bodies are executed, the This trait can only have a default value of None. This, and because we always validate default values, allow_none is always true.

class traitlets.ForwardDeclaredInstance(klass: type[T] = ..., args: tuple[Any, ...] | None = ..., kw: dict[str, Any] | None = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: Any)#
class traitlets.ForwardDeclaredInstance(klass: type[T] = ..., args: tuple[Any, ...] | None = ..., kw: dict[str, Any] | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: Any)
class traitlets.ForwardDeclaredInstance(klass: str | None = ..., args: tuple[Any, ...] | None = ..., kw: dict[str, Any] | None = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: Any)
class traitlets.ForwardDeclaredInstance(klass: str | None = ..., args: tuple[Any, ...] | None = ..., kw: dict[str, Any] | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: Any)

Forward-declared version of Instance.

class traitlets.ForwardDeclaredType(default_value: Sentinel | None | str = ..., klass: None | str = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)#
class traitlets.ForwardDeclaredType(default_value: Sentinel | None | str = ..., klass: None | str = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)
class traitlets.ForwardDeclaredType(default_value: S = ..., klass: S = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)
class traitlets.ForwardDeclaredType(default_value: S | None = ..., klass: S = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)

Forward-declared version of Type.

Miscellaneous#

class traitlets.Bool(default_value: bool | Sentinel = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any = ..., **kwargs: Any)#
class traitlets.Bool(default_value: bool | Sentinel | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any = ..., **kwargs: Any)

A boolean (True, False) trait.

class traitlets.CBool#

Casting variant. When a value is assigned to the attribute, this will attempt to convert it by calling value = bool(value).

class traitlets.Enum(values: Sequence[G], default_value: G | Sentinel = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any = ..., **kwargs: Any)#
class traitlets.Enum(values: Sequence[G] | None, default_value: G | Sentinel | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any = ..., **kwargs: Any)

An enum whose value must be in a given sequence.

class traitlets.CaselessStrEnum(values: Any, default_value: Any = traitlets.Undefined, **kwargs: Any)#

An enum of strings where the case should be ignored.

class traitlets.UseEnum(enum_class: type[Any], default_value: Any = None, **kwargs: Any)#

Use a Enum class as model for the data type description. Note that if no default-value is provided, the first enum-value is used as default-value.

# -- SINCE: Python 3.4 (or install backport: pip install enum34)
import enum
from traitlets import HasTraits, UseEnum


class Color(enum.Enum):
    red = 1  # -- IMPLICIT: default_value
    blue = 2
    green = 3


class MyEntity(HasTraits):
    color = UseEnum(Color, default_value=Color.blue)


entity = MyEntity(color=Color.red)
entity.color = Color.green  # USE: Enum-value (preferred)
entity.color = "green"  # USE: name (as string)
entity.color = "Color.green"  # USE: scoped-name (as string)
entity.color = 3  # USE: number (as int)
assert entity.color is Color.green
class traitlets.TCPAddress(default_value: bool | Sentinel = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any = ..., **kwargs: Any)#
class traitlets.TCPAddress(default_value: bool | None | Sentinel = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: Any = ..., **kwargs: Any)

A trait for an (ip, port) tuple.

This allows for both IPv4 IP addresses as well as hostnames.

class traitlets.CRegExp(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: Any = None, **kwargs: Any)#

A casting compiled regular expression trait.

Accepts both strings and compiled regular expressions. The resulting attribute will be a compiled regular expression.

class traitlets.Union(trait_types: Any, **kwargs: Any)#

A trait type representing a Union type.

__init__(trait_types: Any, **kwargs: Any) None#

Construct a Union trait.

This trait allows values that are allowed by at least one of the specified trait types. A Union traitlet cannot have metadata on its own, besides the metadata of the listed types.

Parameters:
  • trait_types (sequence) – The list of trait types of length at least 1.

  • **kwargs – Extra kwargs passed to TraitType

Notes

Union([Float(), Bool(), Int()]) attempts to validate the provided values with the validation function of Float, then Bool, and finally Int.

Parsing from string is ambiguous for container types which accept other collection-like literals (e.g. List accepting both [] and () precludes Union from ever parsing Union([List(), Tuple()]) as a tuple; you can modify behaviour of too permissive container traits by overriding _literal_from_string_pairs in subclasses. Similarly, parsing unions of numeric types is only unambiguous if types are provided in order of increasing permissiveness, e.g. Union([Int(), Float()]) (since floats accept integer-looking values).

class traitlets.Callable(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: Any = None, **kwargs: Any)#

A trait which is callable.

Notes

Classes are callable, as are instances with a __call__() method.

class traitlets.Any(default_value: Any = ..., *, allow_none: Literal[False], read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)#
class traitlets.Any(default_value: Any = ..., *, allow_none: Literal[True], read_only: bool | None = ..., help: str | None = ..., config: Any | None = ..., **kwargs: Any)
class traitlets.Any(default_value: Any = ..., *, allow_none: Literal[True, False] = ..., help: str | None = ..., read_only: bool | None = False, config: Any = None, **kwargs: Any)

A trait which allows any value.