Using Traitlets

Any class with trait attributes must inherit from HasTraits.

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

The base class for all classes that have traitlets.

has_trait(name)

Returns True if the object has a trait with the specified name.

trait_names(**metadata)

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

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.

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.

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.

trait_metadata(traitname, key, default=None)

Get metadata values for trait by key.

add_traits(**traits)

Dynamically add trait attributes to the HasTraits instance.

You then declare the trait attributes on the class like this:

from traitlets import HasTraits, Int, Unicode

class Requester(HasTraits):
    url = Unicode()
    timeout = Int(30)  # 30 will be the default value

For the available trait types and the arguments you can give them, see Trait Types.

Dynamic default values

To calculate a default value dynamically, decorate a method of your class with @default({traitname}). This method will be called on the instance, and should return the default value. For example:

import getpass

class Identity(HasTraits):
    username = Unicode()

    @default('username')
    def _username_default(self):
        return getpass.getuser()

Callbacks when trait attributes change

To do something when a trait attribute is changed, decorate a method with traitlets.observe(). The method will be called with a single argument, a dictionary of the form:

{
  'owner': object, # The HasTraits instance
  'new': 6, # The new value
  'old': 5, # The old value
  'name': "foo", # The name of the changed trait
  'type': 'change', # The event type of the notification, usually 'change'
}

For example:

from traitlets import HasTraits, Integer, observe

class TraitletsExample(HasTraits):
    num = Integer(5, help="a number").tag(config=True)

    @observe('num')
    def _num_changed(self, change):
        print("{name} changed from {old} to {new}".format(**change))

Changed in version 4.1: The _{trait}_changed magic method-name approach is deprecated.

You can also add callbacks to a trait dynamically:

Note

If a trait attribute with a dynamic default value has another value set before it is used, the default will not be calculated. Any callbacks on that trait will will fire, and old_value will be None.