Warning

This documentation is for an old version of IPython. You can find docs for newer versions here.

Module: utils.traitlets

A lightweight Traits like module.

This is designed to provide a lightweight, simple, pure Python version of many of the capabilities of enthought.traits. This includes:

  • Validation
  • Type specification with defaults
  • Static and dynamic notification
  • Basic predefined types
  • An API that is similar to enthought.traits

We don’t support:

  • Delegation
  • Automatic GUI generation
  • A full set of trait types. Most importantly, we don’t provide container traits (list, dict, tuple) that can trigger notifications if their contents change.
  • API compatibility with enthought.traits

There are also some important difference in our design:

  • enthought.traits does not validate default values. We do.

We choose to create this module because we need these capabilities, but we need them to be pure Python so they work in all Python implementations, including Jython and IronPython.

Inheritance diagram:

Inheritance diagram of IPython.utils.traitlets

46 Classes

IPython.utils.traitlets.NoDefaultSpecified
IPython.utils.traitlets.Undefined
class IPython.utils.traitlets.TraitError

Bases: Exception

Bases: object

Link traits from different objects together so they remain in sync.

Parameters:*args : pairs of objects/attributes

Examples

>>> c = link((obj1, 'value'), (obj2, 'value'), (obj3, 'value'))
>>> obj1.value = 5 # updates other objects as well
__init__(*args)

Bases: object

Link the trait of a source object with traits of target objects.

Parameters:

source : pair of object, name

targets : pairs of objects/attributes

Examples

>>> c = directional_link((src, 'value'), (tgt1, 'value'), (tgt2, 'value'))
>>> src.value = 5  # updates target objects
>>> tgt1.value = 6 # does not update other objects
__init__(source, *targets)
class IPython.utils.traitlets.TraitType(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: object

A base class for all trait descriptors.

Notes

Our implementation of traits is based on Python’s descriptor prototol. This class is the base class for all such descriptors. The only magic we use is a custom metaclass for the main HasTraits class that does the following:

  1. Sets the name attribute of every TraitType instance in the class dict to the name of the attribute.
  2. Sets the this_class attribute of every TraitType instance in the class dict to the class that declared the trait. This is used by the This trait to allow subclasses to accept superclasses for This values.
__init__(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Create a TraitType.

get_default_value()

Create a new instance of the default value.

instance_init(obj)

This is called by HasTraits.__new__() to finish init’ing.

Some stages of initialization must be delayed until the parent HasTraits instance has been created. This method is called in HasTraits.__new__() after the instance has been created.

This method trigger the creation and validation of default values and also things like the resolution of str given class names in Type and :class`Instance`.

Parameters:

obj : HasTraits instance

The parent HasTraits instance that has just been created.

set_default_value(obj)

Set the default value on a per instance basis.

This method is called by instance_init() to create and validate the default value. The creation and validation of default values must be delayed until the parent HasTraits class has been instantiated.

class IPython.utils.traitlets.MetaHasTraits(name, bases, classdict)

Bases: type

A metaclass for HasTraits.

This metaclass makes sure that any TraitType class attributes are instantiated and sets their name attribute.

__init__(name, bases, classdict)

Finish initializing the HasTraits class.

This sets the this_class attribute of each TraitType in the class dict to the newly created class cls.

class IPython.utils.traitlets.HasTraits(*args, **kw)

Bases: IPython.utils.traitlets._NewBase

__init__(*args, **kw)
classmethod class_trait_names(**metadata)

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata)

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. This does not allow for any simple way of testing that a metadata name exists and has any value because get_metadata returns None if a metadata key doesn’t exist.

on_trait_change(handler, name=None, remove=False)

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

Parameters:

handler : callable

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new) or handler(name, old, new).

name : list, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

remove : bool

If False (the default), then install the handler. If True then unintall it.

trait_metadata(traitname, key, default=None)

Get metadata values for trait by key.

trait_names(**metadata)

Get a list of all the names of this class’ traits.

traits(**metadata)

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. This does not allow for any simple way of testing that a metadata name exists and has any value because get_metadata returns None if a metadata key doesn’t exist.

class IPython.utils.traitlets.ClassBasedTraitType(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

A trait with error reporting and string -> type resolution for Type, Instance and This.

class IPython.utils.traitlets.Type(default_value=None, klass=None, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.ClassBasedTraitType

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

__init__(default_value=None, klass=None, allow_none=True, **metadata)

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.

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, None

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

Indicates whether None is allowed as an assignable value. Even if False, the default value may be None.

info()

Returns a description of the trait.

validate(obj, value)

Validates that the value is a valid object instance.

class IPython.utils.traitlets.DefaultValueGenerator(*args, **kw)

Bases: object

A class for generating new default value instances.

__init__(*args, **kw)
class IPython.utils.traitlets.Instance(klass=None, args=None, kw=None, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.ClassBasedTraitType

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, allow_none=True, **metadata)

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

Indicates whether None is allowed as a value.

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.

get_default_value()

Instantiate a default value instance.

This is called when the containing HasTraits classes’ __new__() method is called to ensure that a unique instance is created for each HasTraits instance.

class IPython.utils.traitlets.ForwardDeclaredMixin

Bases: object

Mixin for forward-declared versions of Instance and Type.

class IPython.utils.traitlets.ForwardDeclaredType(default_value=None, klass=None, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.ForwardDeclaredMixin, IPython.utils.traitlets.Type

Forward-declared version of Type.

class IPython.utils.traitlets.ForwardDeclaredInstance(klass=None, args=None, kw=None, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.ForwardDeclaredMixin, IPython.utils.traitlets.Instance

Forward-declared version of Instance.

class IPython.utils.traitlets.This(**metadata)

Bases: IPython.utils.traitlets.ClassBasedTraitType

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.

__init__(**metadata)
class IPython.utils.traitlets.Union(trait_types, **metadata)

Bases: IPython.utils.traitlets.TraitType

A trait type representing a Union type.

__init__(trait_types, **metadata)

Construct a Union trait.

This trait allows values that are allowed by at least one of the specified trait types.

Parameters:

trait_types: sequence

The list of trait types of length at least 1.

Notes

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

class IPython.utils.traitlets.Any(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

class IPython.utils.traitlets.Int(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

An int trait.

class IPython.utils.traitlets.CInt(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.Int

A casting version of the int trait.

IPython.utils.traitlets.Long

alias of Int

IPython.utils.traitlets.CLong

alias of CInt

IPython.utils.traitlets.Integer

alias of Int

class IPython.utils.traitlets.Float(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

A float trait.

class IPython.utils.traitlets.CFloat(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.Float

A casting version of the float trait.

class IPython.utils.traitlets.Complex(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

A trait for complex numbers.

class IPython.utils.traitlets.CComplex(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.Complex

A casting version of the complex number trait.

class IPython.utils.traitlets.Bytes(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

A trait for byte strings.

class IPython.utils.traitlets.CBytes(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.Bytes

A casting version of the byte string trait.

class IPython.utils.traitlets.Unicode(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

A trait for unicode strings.

class IPython.utils.traitlets.CUnicode(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.Unicode

A casting version of the unicode trait.

class IPython.utils.traitlets.ObjectName(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

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

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

class IPython.utils.traitlets.DottedObjectName(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.ObjectName

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

class IPython.utils.traitlets.Bool(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

A boolean (True, False) trait.

class IPython.utils.traitlets.CBool(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.Bool

A casting version of the boolean trait.

class IPython.utils.traitlets.Enum(values, default_value=None, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.TraitType

An enum that whose value must be in a given sequence.

__init__(values, default_value=None, allow_none=True, **metadata)
info()

Returns a description of the trait.

class IPython.utils.traitlets.CaselessStrEnum(values, default_value=None, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.Enum

An enum of strings that are caseless in validate.

class IPython.utils.traitlets.Container(trait=None, default_value=None, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.Instance

An instance of a container (list, set, etc.)

To be subclassed by overriding klass.

__init__(trait=None, default_value=None, allow_none=True, **metadata)

Create a container 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.

allow_none : Bool [ default True ]

Whether to allow the value to be None

**metadata : any

further keys for extensions to the Trait (e.g. config)

class IPython.utils.traitlets.List(trait=None, default_value=None, minlen=0, maxlen=9223372036854775807, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.Container

An instance of a Python list.

__init__(trait=None, default_value=None, minlen=0, maxlen=9223372036854775807, allow_none=True, **metadata)

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

allow_none : Bool [ default True ]

Whether to allow the value to be None

**metadata : any

further keys for extensions to the Trait (e.g. config)

klass

alias of list

class IPython.utils.traitlets.Set(trait=None, default_value=None, minlen=0, maxlen=9223372036854775807, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.List

An instance of a Python set.

klass

alias of set

class IPython.utils.traitlets.Tuple(*traits, **metadata)

Bases: IPython.utils.traitlets.Container

An instance of a Python tuple.

__init__(*traits, default_value=None, allow_none=True, **medatata)

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, the default_value must conform to the shape and type they specify.

allow_none : Bool [ default True ]

Whether to allow the value to be None

**metadata : any

further keys for extensions to the Trait (e.g. config)

klass

alias of tuple

class IPython.utils.traitlets.Dict(default_value={}, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.Instance

An instance of a Python dict.

__init__(default_value={}, allow_none=True, **metadata)

Create a dict trait type from a dict.

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

class IPython.utils.traitlets.EventfulDict(default_value={}, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.Instance

An instance of an EventfulDict.

__init__(default_value={}, allow_none=True, **metadata)

Create a EventfulDict trait type from a dict.

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

class IPython.utils.traitlets.EventfulList(default_value=None, allow_none=True, **metadata)

Bases: IPython.utils.traitlets.Instance

An instance of an EventfulList.

__init__(default_value=None, allow_none=True, **metadata)

Create a EventfulList trait type from a dict.

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

class IPython.utils.traitlets.TCPAddress(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

A trait for an (ip, port) tuple.

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

class IPython.utils.traitlets.CRegExp(default_value=<IPython.utils.traitlets.NoDefaultSpecified object>, allow_none=None, **metadata)

Bases: IPython.utils.traitlets.TraitType

A casting compiled regular expression trait.

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

6 Functions

IPython.utils.traitlets.class_of(object)

Returns a string containing the class name of an object with the correct indefinite article (‘a’ or ‘an’) preceding it (e.g., ‘an Image’, ‘a PlotValue’).

IPython.utils.traitlets.add_article(name)

Returns a string containing the correct indefinite article (‘a’ or ‘an’) prefixed to the specified string.

IPython.utils.traitlets.repr_type(obj)

Return a string representation of a value and its type for readable error messages.

IPython.utils.traitlets.is_trait(t)

Returns whether the given value is an instance or subclass of TraitType.

IPython.utils.traitlets.parse_notifier_name(name)

Convert the name argument to a list of names.

Examples

>>> parse_notifier_name('a')
['a']
>>> parse_notifier_name(['a','b'])
['a', 'b']
>>> parse_notifier_name(None)
['anytrait']
IPython.utils.traitlets.getmembers(object, predicate=None)

A safe version of inspect.getmembers that handles missing attributes.

This is useful when there are descriptor based attributes that for some reason raise AttributeError even though they exist. This happens in zope.inteface with the __provides__ attribute.