# Trait Types

class traitlets.TraitType

  The base class for all trait types.

  __init__(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

    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.

    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)

    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

    New 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=traitlets.Undefined, allow_none=False, **kwargs)

  A float trait.

class traitlets.Complex(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

  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=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

  A trait for unicode strings.

class traitlets.Bytes(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

  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=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

  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=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

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

## Containers

class traitlets.List(trait=None, default_value=traitlets.Undefined, minlen=0, maxlen=9223372036854775807, **kwargs)

  An instance of a Python list.

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

    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)

    Return the value from a list of config strings

    This is where we parse CLI configuration

  item_from_string(s, index=None)

    Cast a single item from a string

    Evaluated when parsing CLI configuration from a string

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

  An instance of a Python set.

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

    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, **kwargs)

  An instance of a Python tuple.

  __init__(*traits, **kwargs)

    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=None, per_key_traits=None, key_trait=None, default_value=traitlets.Undefined, **kwargs)

  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=None, per_key_traits=None, key_trait=None, default_value=traitlets.Undefined, **kwargs)

    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)

    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)

    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=None, args=None, kw=None, **kwargs)

  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=None, args=None, kw=None, **kwargs)

    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=traitlets.Undefined, klass=None, **kwargs)

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

  __init__(default_value=traitlets.Undefined, klass=None, **kwargs)

    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)

  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=None, args=None, kw=None, **kwargs)

  Forward-declared version of Instance.

class traitlets.ForwardDeclaredType(default_value=traitlets.Undefined, klass=None, **kwargs)

  Forward-declared version of Type.

## Miscellaneous

class traitlets.Bool(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

  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, default_value=traitlets.Undefined, **kwargs)

  An enum whose value must be in a given sequence.

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

  An enum of strings where the case should be ignored.

class traitlets.UseEnum(enum_class, default_value=None, **kwargs)

  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=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

  A trait for an (ip, port) tuple.

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

class traitlets.CRegExp(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

  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, **kwargs)

  A trait type representing a Union type.

  __init__(trait_types, **kwargs)

    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=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

  A trait which is callable.

  Notes

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

class traitlets.Any(default_value=traitlets.Undefined, allow_none=False, read_only=None, help=None, config=None, **kwargs)

  A trait which allows any value.

previous

Using Traitlets

next

Defining new trait types