[TransWarp] Constraints on model attributes

Phillip J. Eby pje at telecommunity.com
Sun Jul 27 15:20:05 EDT 2003

At 12:43 PM 7/27/03 +0200, Roché Compaan wrote:

>I've played around more and _onLink and _onUnlink methods are the
>perfect place for validation and constraint hooks. I don't think
>anything needs to be done to model features or datatypes. Here's a
>crude example:
>class TextLine(model.Attribute):
>     referencedType = model.String
>     title = u''
>     description = u''
>     def constraint(self, value):
>         return '\n' not in value and '\r' not in value
>     def _validate(self, element, item):
>         if not isinstance(item, unicode):
>             raise TypeError
>         if self.constraint is not None and not self.constraint(item):
>             raise ValidationError
>     def _onLink(self, element, item, posn):
>         self._validate(element, item)
>class Person(model.Element):
>     class Name(TextLine):
>         title = u'Name'
>         description = u'''Person's name'''
>Do you see any problem with this approach?

Not as such; but it would be a lot simpler this way:

class TextLine(model.String):

     def mdl_normalize(klass, value):
         value = unicode(value)   # this should raise TypeError if not 
         if '\n' in value or '\r' in value:
             raise ValueError("Multi-line text")
         return value

class Person(model.Element):
     class Name(model.Attribute):
         referencedType = TextLine
         # ...

This is somewhat more reusable, as well.  I prefer to distinguish between 
constraints applying to the *type* of the feature, and those that are 
specific to the feature itself.  The latter kind usually involve conditions 
imposed by other features of the same object.

More information about the PEAK mailing list