Traits

7.1.0 · active · verified Mon Apr 13

Traits is a Python library that enables the definition of observable typed attributes for Python classes. It provides features like initialization with default values, validation of assigned values, delegation, notification upon value changes, and automatic user interface generation for attribute modification. Traits is a core component of the Enthought Tool Suite and aims to enhance code clarity and reduce boilerplate, particularly in scientific and engineering applications. The current stable version is 7.1.0, and it generally follows a regular release cadence with major updates addressing Python version compatibility and API refinements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a class with various trait types (Str, Int, Float), setting default values, providing a description, and using an observer to react to trait changes. It also shows how Traits enforces type validation, raising a TraitError on invalid assignments.

from traits.api import HasTraits, Str, Float, observe

class Person(HasTraits):
    name = Str('John Doe')
    age = Int(30)
    height = Float(175.0, desc='Height in cm')

    @observe('age')
    def _age_changed(self, event):
        print(f"Age changed from {event.old} to {event.new}")

# Create an instance
joe = Person(name='Joe', age=25)
print(f"Initial: {joe.name}, {joe.age}, {joe.height}")

# Modify trait attributes
joe.age = 26 # This will trigger the observer
joe.height = 180.5
print(f"Updated: {joe.name}, {joe.age}, {joe.height}")

# Attempt invalid assignment (will raise TraitError)
try:
    joe.age = "thirty"
except Exception as e:
    print(f"Error: {e}")

view raw JSON →