Traits
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
- breaking Python versions earlier than 3.8 are no longer supported since Traits 7.0.0. If you are on an older Python version, you must upgrade Python or use an older Traits version (e.g., Traits 6.x for Python 3.7).
- breaking The behavior of default list or dict values for the `Any` trait type changed in Traits 7.0.0. Previously, a per-instance copy was provided; now, the default value is shared between all instances. This can lead to unexpected shared state across objects if not handled carefully.
- breaking The `Date` trait type no longer accepts `datetime` instances by default since Traits 7.0.0. Assignments of `datetime` objects to `Date` traits will raise a `TraitError`.
- deprecated The `HasTraits.get()` and `HasTraits.set()` methods were removed in Traits 7.0.0. These methods were used for accessing and modifying trait values programmatically.
- deprecated The `Trait()` function for creating trait definitions is deprecated and not recommended for new code. It may be removed in future versions.
Install
-
pip install traits
Imports
- HasTraits
from traits.api import HasTraits
- Str
from traits.api import Str
- Int
from traits.api import Int
- Float
from traits.api import Float
- Color
from traitsui.api import Color
- Trait
from traits.api import Union
Quickstart
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}")