Trait Types for SciPy and NumPy
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
- gotcha The `traittypes` project is in maintenance mode and has not seen significant development since early 2021. Users should be aware that new features or bug fixes are unlikely to be implemented.
- gotcha When assigning NumPy arrays to `Array` traits, the array object itself is stored; `traittypes` (like `traitlets`) does not create a deep copy by default. This means modifying the assigned array externally will reflect in the trait's value.
- gotcha `traittypes` relies on `traitlets`' coercion mechanisms. Values assigned to traits may be implicitly converted to the expected type (e.g., a list might be converted to a NumPy array). This can sometimes hide subtle type mismatches if strict type checking is expected.
Install
-
pip install traittypes
Imports
- Array
from traittypes import Array
- ArrayType
from traittypes import ArrayType
- ScipySparse
from traittypes import ScipySparse
- ScipySparseType
from traittypes import ScipySparseType
Quickstart
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}")