Trait Types for SciPy and NumPy

0.2.3 · maintenance · verified Sat Apr 11

traittypes provides trait types extending the `traitlets` library, specifically designed for common data structures in the SciPy ecosystem, such as NumPy arrays and SciPy sparse matrices. It allows developers to define robust type-checked attributes for these data types in `traitlets`-based classes. The current version is 0.2.3. The library appears to be in maintenance mode, with no significant development since early 2021, meaning new features or bug fixes are infrequent.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a `HasTraits` class with `traittypes.Array` attributes. It shows how to assign NumPy arrays, enforce dimensionality with custom validation, and utilize the `shape` keyword argument for structural constraints.

from traitlets import HasTraits, validate, TraitError
from traittypes import Array
import numpy as np

class DataContainer(HasTraits):
    data = Array(help="A NumPy array container.")
    matrix_shape = Array(shape=(2,), help="Shape of a matrix (rows, cols).")

    @validate('data')
    def _valid_data(self, proposal):
        if proposal['value'].ndim != 1:
            raise TraitError('data must be a 1D array.')
        return proposal['value']

# Instantiate the container
container = DataContainer()

# Assign a valid array
container.data = np.array([1, 2, 3, 4])
print(f"Assigned 1D data: {container.data}")

# Attempt to assign an invalid array (will raise TraitError)
try:
    container.data = np.array([[1, 2], [3, 4]])
except TraitError as e:
    print(f"Error assigning 2D data: {e}")

# Assign a valid shape array
container.matrix_shape = np.array([10, 20])
print(f"Assigned matrix_shape: {container.matrix_shape}")

# Attempt to assign an invalid shape array (will raise TraitError due to 'shape' constraint)
try:
    container.matrix_shape = np.array([5, 6, 7])
except TraitError as e:
    print(f"Error assigning wrong shape: {e}")

view raw JSON →