# Traitlets API reference

Any class with trait attributes must inherit from `HasTraits`.

class traitlets.HasTraits(**kwargs: Any)
  has_trait(name)

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

  trait_has_value(name)

    Returns True if the specified trait has a value.

    This will return false even if `getattr` would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

    Example

        class MyClass(HasTraits):
            i = Int()

        mc = MyClass()
        assert not mc.trait_has_value("i")
        mc.i # generates a default value
        assert mc.trait_has_value("i")

  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. If a metadata key doesn’t exist, None will be passed to the function.

  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. If a metadata key doesn’t exist, None will be passed to the function.

  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

traitlets.default(name)

  A decorator which assigns a dynamic default for a Trait on a HasTraits object.

  Parameters:

    name – The str name of the Trait on the object whose default should be generated.

  Notes

  Unlike observers and validators which are properties of the HasTraits instance, default value generators are class-level properties.

  Besides, default generators are only invoked if they are registered in subclasses of this_type.

      class A(HasTraits):
          bar = Int()

          @default('bar')
          def get_bar_default(self):
              return 11

      class B(A):
          bar = Float()  # This trait ignores the default generator defined in
                         # the base class A

      class C(B):

          @default('bar')
          def some_other_default(self):  # This default generator should not be
              return 3.0                 # ignored since it is defined in a
                                         # class derived from B.a.this_class.

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

traitlets.observe(*names, type='change')

  A decorator which can be used to observe Traits on a class.

  The handler passed to the decorator will be called with one `change` dict argument. The change dictionary at least holds a ‘type’ key and a ‘name’ key, corresponding respectively to the type of notification and the name of the attribute that triggered the notification.

  Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * `owner` : the HasTraits instance * `old` : the old value of the modified trait attribute * `new` : the new value of the modified trait attribute * `name` : the name of the modified trait attribute.

  Parameters:

    - *names – The str names of the Traits to observe on the object.

    - type (str, kwarg-only) – The type of event to observe (e.g. ‘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:

HasTraits.observe(handler, names=traitlets.All, type='change')

  Setup a handler to be called when a trait changes.

  This is used to setup dynamic notifications of trait changes.

  Parameters:

    - handler (callable) – A callable that is called when a trait changes. Its signature should be `handler(change)`, where `change` is a dictionary. The change dictionary at least holds a ‘type’ key. * `type`: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * `owner` : the HasTraits instance * `old` : the old value of the modified trait attribute * `new` : the new value of the modified trait attribute * `name` : the name of the modified trait attribute.

    - names (list, str, All) – If names is All, 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.

    - type (str, All (default: 'change')) – The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

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

## Validating proposed changes

traitlets.validate(*names)

  A decorator to register cross validator of HasTraits object’s state when a Trait is set.

  The handler passed to the decorator must have one `proposal` dict argument. The proposal dictionary must hold the following keys:

  - `owner` : the HasTraits instance

  - `value` : the proposed value for the modified trait attribute

  - `trait` : the TraitType instance associated with the attribute

  Parameters:

    *names – The str names of the Traits to validate.

  Notes

  Since the owner has access to the `HasTraits` instance via the ‘owner’ key, the registered cross validator could potentially make changes to attributes of the `HasTraits` instance. However, we recommend not to do so. The reason is that the cross-validation of attributes may run in arbitrary order when exiting the `hold_trait_notifications` context, and such changes may not commute.

Validator methods can be used to enforce certain aspects of a property. These are called on proposed changes, and can raise a TraitError if the change should be rejected, or coerce the value if it should be accepted with some modification. This can be useful for things such as ensuring a path string is always absolute, or check if it points to an existing directory.

For example:

    from traitlets import HasTraits, Unicode, validate, TraitError

    class TraitletsExample(HasTraits):
        path = Unicode('', help="a path")

        @validate('path')
        def _check_prime(self, proposal):
            path = proposal['value']
            if not path.endswith('/'):
                # ensure path always has trailing /
                path = path + '/'
            if not os.path.exists(path):
                raise TraitError("path %r does not exist" % path)
            return path

previous

Defining new trait types

next

Configurable objects with traitlets.config