Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
foo.bar = [1, 2] # Should raise a TraitError
"""
self.validators.extend(validators)
return self
def validate(self, obj, value):
"""Validate the value against registered validators."""
try:
for validator in self.validators:
value = validator(self, value)
return value
except (ValueError, TypeError) as e:
raise TraitError(e)
class Array(SciType):
"""A numpy array trait type."""
info_text = 'a numpy array'
dtype = None
def validate(self, obj, value):
if value is None and not self.allow_none:
self.error(obj, value)
if value is None or value is Undefined:
return super(Array, self).validate(obj, value)
try:
r = np.asarray(value, dtype=self.dtype)
if isinstance(value, np.ndarray) and r is not value:
warnings.warn(
'Given trait value dtype "%s" does not match required type "%s". '
def __init__(self, **kwargs):
super(SciType, self).__init__(**kwargs)
self.validators = []
"""A pandas series trait type."""
info_text = 'a pandas series'
dtype = None
def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs):
if 'klass' not in kwargs and self.klass is None:
import pandas as pd
kwargs['klass'] = pd.Series
super(Series, self).__init__(
default_value=default_value, allow_none=allow_none, dtype=dtype, **kwargs)
self.dtype = dtype
class XarrayType(SciType):
"""An xarray dataset or dataarray trait type."""
info_text = 'an xarray dataset or dataarray'
klass = None
def validate(self, obj, value):
if value is None and not self.allow_none:
self.error(obj, value)
if value is None or value is Undefined:
return super(XarrayType, self).validate(obj, value)
try:
value = self.klass(value)
except (ValueError, TypeError) as e:
raise TraitError(e)
def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs):
self.dtype = dtype
if default_value is Empty:
default_value = np.array(0, dtype=self.dtype)
elif default_value is not None and default_value is not Undefined:
default_value = np.asarray(default_value, dtype=self.dtype)
super(Array, self).__init__(default_value=default_value, allow_none=allow_none, **kwargs)
def make_dynamic_default(self):
if self.default_value is None or self.default_value is Undefined:
return self.default_value
else:
return np.copy(self.default_value)
class PandasType(SciType):
"""A pandas dataframe or series trait type."""
info_text = 'a pandas dataframe or series'
klass = None
def validate(self, obj, value):
if value is None and not self.allow_none:
self.error(obj, value)
if value is None or value is Undefined:
return super(PandasType, self).validate(obj, value)
try:
value = self.klass(value)
except (ValueError, TypeError) as e:
raise TraitError(e)