Пример #1
0
 def validate(self, object, name, value):
     try:
         if isinstance(value, tuple):
             traits = self.traits
             if len(value) == len(traits):
                 values = []
                 for i, trait in enumerate(traits):
                     values.append(
                         trait.handler.validate(object, name, value[i]))
                 return tuple(values)
     except:
         pass
     self.error(object, name, self.repr(value))
Пример #2
0
 def validate ( self, object, name, value ):
     try:
         if isinstance( value, tuple ):
             traits = self.traits
             if len( value ) == len( traits ):
                 values = []
                 for i, trait in enumerate( traits ):
                     values.append( trait.handler.validate( object, name,
                                                            value[i] ) )
                 return tuple( values )
     except:
         pass
     self.error( object, name, self.repr( value ) ) 
Пример #3
0
    def validate ( self, object, name, value ):
        """ Validates that a value is legal for the trait.
        """
        #try:
        if 1:
            # Make sure the value is an array:
            type_value = type( value )
            if not isinstance( value, ndarray ): 
                if not isinstance(value, (list,tuple)):
                    self.error( object, name, self.repr( value ) ) 
                if self.dtype is not None:
                    value = asarray(value, self.dtype)
                else:
                    value = asarray(value)
                
            # Make sure the array is of the right type:
            if ((self.dtype is not None) and 
                (value.dtype != self.dtype)):
                if self.coerce:
                    value = value.astype( self.dtype )
                else:
                    value = asarray( value, self.dtype )
                    
            # If no shape requirements, then return the value:
            trait_shape = self.shape
            if trait_shape is None:
                return value
                
            # Else make sure that the value's shape is compatible:
            value_shape = value.shape
            if len( trait_shape ) == len( value_shape ):
                for i, dim in enumerate( value_shape ):
                    item = trait_shape[i]
                    if item is not None:
                        if type( item ) is int:
                            if dim != item:
                                break
                        elif ((dim < item[0]) or 
                              ((item[1] is not None) and (dim > item[1]))):
                            break
                else:
                    return value

        #    print "*** pass through"
        #except Exception, e:
        #    print "*** exception:", e
        self.error( object, name, self.repr( value ) ) 
Пример #4
0
    def validate(self, object, name, value):
        """ Validates that a value is legal for the trait.
        """
        #try:
        if 1:
            # Make sure the value is an array:
            type_value = type(value)
            if not isinstance(value, ndarray):
                if not isinstance(value, (list, tuple)):
                    self.error(object, name, self.repr(value))
                if self.dtype is not None:
                    value = asarray(value, self.dtype)
                else:
                    value = asarray(value)

            # Make sure the array is of the right type:
            if ((self.dtype is not None) and (value.dtype != self.dtype)):
                if self.coerce:
                    value = value.astype(self.dtype)
                else:
                    value = asarray(value, self.dtype)

            # If no shape requirements, then return the value:
            trait_shape = self.shape
            if trait_shape is None:
                return value

            # Else make sure that the value's shape is compatible:
            value_shape = value.shape
            if len(trait_shape) == len(value_shape):
                for i, dim in enumerate(value_shape):
                    item = trait_shape[i]
                    if item is not None:
                        if type(item) is int:
                            if dim != item:
                                break
                        elif ((dim < item[0])
                              or ((item[1] is not None) and (dim > item[1]))):
                            break
                else:
                    return value

        #    print "*** pass through"
        #except Exception, e:
        #    print "*** exception:", e
        self.error(object, name, self.repr(value))
Пример #5
0
 def validate ( self, object, name, value ):
     """ Validates that a value is legal for the trait.
     """
     try:
         # Make sure the value is an array:
         type_value = type( value )
         if type_value is not ArrayType:
             if type_value not in SequenceTypes:
                 self.error( object, name, self.repr( value ) ) 
             value = asarray( value, self.typecode )
             
         # Make sure the array is of the right type:
         if ((self.typecode is not None) and 
             (value.typecode() != self.typecode)):
             if self.coerce:
                 value = value.astype( self.typecode )
             else:
                 value = asarray( value, self.typecode )
                 
         # If no shape requirements, then return the value:
         trait_shape = self.shape
         if trait_shape is None:
             return value
             
         # Else make sure that the value's shape is compatible:
         value_shape = value.shape
         if len( trait_shape ) == len( value_shape ):
             for i, dim in enumerate( value_shape ):
                 item = trait_shape[i]
                 if item is not None:
                     if type( item ) is int:
                         if dim != item:
                             break
                     elif ((dim < item[0]) or 
                           ((item[1] is not None) and (dim > item[1]))):
                         break
             else:
                 return value
     except:
         pass
     self.error( object, name, self.repr( value ) ) 
Пример #6
0
    def validate(self, object, name, value):
        """ Validates that a value is legal for the trait.
        """
        try:
            # Make sure the value is an array:
            type_value = type(value)
            if type_value is not ArrayType:
                if type_value not in SequenceTypes:
                    self.error(object, name, self.repr(value))
                value = asarray(value, self.typecode)

            # Make sure the array is of the right type:
            if ((self.typecode is not None)
                    and (value.typecode() != self.typecode)):
                if self.coerce:
                    value = value.astype(self.typecode)
                else:
                    value = asarray(value, self.typecode)

            # If no shape requirements, then return the value:
            trait_shape = self.shape
            if trait_shape is None:
                return value

            # Else make sure that the value's shape is compatible:
            value_shape = value.shape
            if len(trait_shape) == len(value_shape):
                for i, dim in enumerate(value_shape):
                    item = trait_shape[i]
                    if item is not None:
                        if type(item) is int:
                            if dim != item:
                                break
                        elif ((dim < item[0])
                              or ((item[1] is not None) and (dim > item[1]))):
                            break
                else:
                    return value
        except:
            pass
        self.error(object, name, self.repr(value))
Пример #7
0
    def define ( self, *value_type, **metadata ):
        default_value_type = -1
        default_value      = handler = clone = None
        if len( value_type ) > 0:
            default_value = value_type[0]
            value_type    = value_type[1:]
            if ((len( value_type ) == 0) and 
                (type( default_value ) in SequenceTypes)):
                default_value, value_type = default_value[0], default_value
            if len( value_type ) == 0:
                if isinstance( default_value, TraitFactory ):
                    default_value = trait_factory( default_value )
                if default_value in PythonTypes:
                    handler       = TraitType( default_value )
                    default_value = DefaultValues.get( default_value )
                elif isinstance( default_value, CTrait ):
                    clone = default_value
                    default_value_type, default_value = clone.default_value()
                    metadata[ 'type' ] = clone.type
                elif isinstance( default_value, TraitHandler ):
                    handler       = default_value
                    default_value = None
                elif default_value is ThisClass:
                    handler       = ThisClass()
                    default_value = None
                else:
                    typeValue = type( default_value )
                    if typeValue is StringType:
                        string_options = self.extract( metadata, 'min_len',
                                                       'max_len', 'regex' )
                        if len( string_options ) == 0:
                            handler = TraitCastType( typeValue )
                        else:
                            handler = TraitString( **string_options )
                    elif typeValue in TypeTypes:
                        handler = TraitCastType( typeValue )
                    else:
                        handler = TraitInstance( default_value )
                        if default_value is handler.aClass:
                            default_value = DefaultValues.get( default_value )
            else:
                enum  = []
                other = []
                map   = {}
                self.do_list( value_type, enum, map, other )
                if (((len( enum )  == 1) and (enum[0] is None)) and
                    ((len( other ) == 1) and 
                     isinstance( other[0], TraitInstance ))):
                    enum = []
                    other[0].allow_none()
                if len( enum ) > 0:
                    if (((len( map ) + len( other )) == 0) and
                        (default_value not in enum)):
                        enum.insert( 0, default_value )
                    other.append( TraitEnum( enum ) )
                if len( map ) > 0:
                    other.append( TraitMap( map ) )
                if len( other ) == 0:
                    handler = TraitHandler()
                elif len( other ) == 1:
                    handler = other[0]
                    if isinstance( handler, CTrait ):
                        clone, handler = handler, None
                        metadata[ 'type' ] = clone.type
                    elif isinstance( handler, TraitInstance ):
                        if default_value is None:
                            handler.allow_none()
                        elif isinstance( default_value, _InstanceArgs ):
                            default_value_type = 7
                            default_value = ( handler.create_default_value, 
                                default_value.args, default_value.kw ) 
                        elif (len( enum ) == 0) and (len( map ) == 0):
                            aClass    = handler.aClass
                            typeValue = type( default_value )
                            if typeValue is dict:
                                default_value_type = 7
                                default_value = ( aClass, (), default_value )
                            elif not isinstance( default_value, aClass ):
                                if typeValue is not tuple:
                                    default_value = ( default_value, )
                                default_value_type = 7
                                default_value = ( aClass, default_value, None )
                else:
                    for i, item in enumerate( other ):
                        if isinstance( item, CTrait ):
                            if item.type != 'trait':
                                raise TraitError, ("Cannot create a complex "
                                    "trait containing %s trait." % 
                                    add_article( item.type ) )
                            handler = item.handler
                            if handler is None:
                                break
                            other[i] = handler
                    else:
                        handler = TraitCompound( other )
 
        # Save the results:
        self.handler = handler
        self.clone   = clone
        if default_value_type < 0:
            if isinstance( default_value, Default ):
                default_value_type = 7
                default_value      = default_value.default_value
            else:
                if (handler is None) and (clone is not None):
                    handler = clone.handler
                if handler is not None:
                    default_value_type = handler.default_value_type
                    if default_value_type >= 0:
                        if hasattr( handler, 'default_value' ):
                            default_value = handler.default_value(default_value)
                    else:
                        try:
                            default_value = handler.validate( None, '',
                                                              default_value )
                        except:
                            pass
                if default_value_type < 0:
                    default_value_type = _default_value_type( default_value )
        self.default_value_type = default_value_type
        self.default_value      = default_value
        self.metadata           = metadata.copy()
Пример #8
0
    def define(self, *value_type, **metadata):
        default_value_type = -1
        default_value = handler = clone = None
        if len(value_type) > 0:
            default_value = value_type[0]
            value_type = value_type[1:]
            if ((len(value_type) == 0)
                    and (type(default_value) in SequenceTypes)):
                default_value, value_type = default_value[0], default_value
            if len(value_type) == 0:
                if isinstance(default_value, TraitFactory):
                    default_value = trait_factory(default_value)
                if default_value in PythonTypes:
                    handler = TraitType(default_value)
                    default_value = DefaultValues.get(default_value)
                elif isinstance(default_value, CTrait):
                    clone = default_value
                    default_value_type, default_value = clone.default_value()
                    metadata['type'] = clone.type
                elif isinstance(default_value, TraitHandler):
                    handler = default_value
                    default_value = None
                elif default_value is ThisClass:
                    handler = ThisClass()
                    default_value = None
                else:
                    typeValue = type(default_value)
                    if typeValue is StringType:
                        string_options = self.extract(metadata, 'min_len',
                                                      'max_len', 'regex')
                        if len(string_options) == 0:
                            handler = TraitCastType(typeValue)
                        else:
                            handler = TraitString(**string_options)
                    elif typeValue in TypeTypes:
                        handler = TraitCastType(typeValue)
                    else:
                        handler = TraitInstance(default_value)
                        if default_value is handler.aClass:
                            default_value = DefaultValues.get(default_value)
            else:
                enum = []
                other = []
                map = {}
                self.do_list(value_type, enum, map, other)
                if (((len(enum) == 1) and (enum[0] is None))
                        and ((len(other) == 1)
                             and isinstance(other[0], TraitInstance))):
                    enum = []
                    other[0].allow_none()
                if len(enum) > 0:
                    if (((len(map) + len(other)) == 0)
                            and (default_value not in enum)):
                        enum.insert(0, default_value)
                    other.append(TraitEnum(enum))
                if len(map) > 0:
                    other.append(TraitMap(map))
                if len(other) == 0:
                    handler = TraitHandler()
                elif len(other) == 1:
                    handler = other[0]
                    if isinstance(handler, CTrait):
                        clone, handler = handler, None
                        metadata['type'] = clone.type
                    elif isinstance(handler, TraitInstance):
                        if default_value is None:
                            handler.allow_none()
                        elif isinstance(default_value, _InstanceArgs):
                            default_value_type = 7
                            default_value = (handler.create_default_value,
                                             default_value.args,
                                             default_value.kw)
                        elif (len(enum) == 0) and (len(map) == 0):
                            aClass = handler.aClass
                            typeValue = type(default_value)
                            if typeValue is dict:
                                default_value_type = 7
                                default_value = (aClass, (), default_value)
                            elif not isinstance(default_value, aClass):
                                if typeValue is not tuple:
                                    default_value = (default_value, )
                                default_value_type = 7
                                default_value = (aClass, default_value, None)
                else:
                    for i, item in enumerate(other):
                        if isinstance(item, CTrait):
                            if item.type != 'trait':
                                raise TraitError, (
                                    "Cannot create a complex "
                                    "trait containing %s trait." %
                                    add_article(item.type))
                            handler = item.handler
                            if handler is None:
                                break
                            other[i] = handler
                    else:
                        handler = TraitCompound(other)

        # Save the results:
        self.handler = handler
        self.clone = clone
        if default_value_type < 0:
            if isinstance(default_value, Default):
                default_value_type = 7
                default_value = default_value.default_value
            else:
                if (handler is None) and (clone is not None):
                    handler = clone.handler
                if handler is not None:
                    default_value_type = handler.default_value_type
                    if default_value_type >= 0:
                        if hasattr(handler, 'default_value'):
                            default_value = handler.default_value(
                                default_value)
                    else:
                        try:
                            default_value = handler.validate(
                                None, '', default_value)
                        except:
                            pass
                if default_value_type < 0:
                    default_value_type = _default_value_type(default_value)
        self.default_value_type = default_value_type
        self.default_value = default_value
        self.metadata = metadata.copy()