[Zope-Checkins] CVS: Zope3/lib/python/Schema - IValidator.py:1.1 Validator.py:1.1 ErrorNames.py:1.3 Exceptions.py:1.4 IField.py:1.2 _Field.py:1.4 _Schema.py:1.4 __init__.py:1.2

Stephan Richter srichter@cbu.edu
Sun, 14 Jul 2002 09:33:23 -0400


Update of /cvs-repository/Zope3/lib/python/Schema
In directory cvs.zope.org:/tmp/cvs-serv5853/Schema

Modified Files:
	ErrorNames.py Exceptions.py IField.py _Field.py _Schema.py 
	__init__.py 
Added Files:
	IValidator.py Validator.py 
Log Message:
- I finished the Schema code. We now have the following Fields defined
  by default: String, Boolean, Integer, Float, Tuple, List, Dictionary

- I also reworked the Validator in a major way. A Validator now does only 
  one thing, such as check that a value has the right type. The Validators
  are then put into a ContainerValidator which runs through all the 
  specified Validators. BTW, I hope you like the code... I do. :)

- Rewrote and added new tests. Note that there are no explicit tests for 
  the Validators, since they are tested already through the Field validate
  method.

- Started working on Forms. There is a whole lot of work to be done there.
  More checkins on that later...


=== Added File Zope3/lib/python/Schema/IValidator.py ===
##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
# 
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
# 
##############################################################################
"""
$Id: IValidator.py,v 1.1 2002/07/14 13:32:53 srichter Exp $
"""
from Interface import Interface

class IValidator(Interface):
    """It's repsonsibility lies in validating a particular value against the
    specifed field. Each Validator just does one check, like check for the
    max value or the min value!

    It should be always implemented as an adapter.
    """

    def validate(value):
        """Validate the the value. Note that this method must always
        return the value.""" 


=== Added File Zope3/lib/python/Schema/Validator.py ===
##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
# 
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
# 
##############################################################################
"""
$Id: Validator.py,v 1.1 2002/07/14 13:32:53 srichter Exp $
"""
from types import ListType, TupleType
ListTypes = (ListType, TupleType)
from Schema.IValidator import IValidator
from Schema.IField import *
from Schema._Field import *

from Schema.Exceptions import StopValidation, ValidationError
import ErrorNames

class Validator:
    """Validator base class"""
    __implements__ =  IValidator

    def __init__(self, field):
        self.field = field
    
    def getDescription(self):
        return self.__doc__

    def validate(self, value):
        'See Schema.IValidator.IValidator'
        return value


class TypeValidator(Validator):
    """Check whether the value is of the correct type."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        t = self.field.type
        if t is not None and value is not None and not isinstance(value, t):
            raise ValidationError, ErrorNames.WrongType
        return value

class RequiredValidator(Validator):
    """If no value was passed, check whether the field was required."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        if value is None:
            if self.field.required:
                raise ValidationError, ErrorNames.RequiredMissing
            else:
                # we are done with validation for sure
                raise StopValidation
        return value

class StringRequiredValidator(Validator):
    """Empty Strings are not acceptable for a required field."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        if self.field.required and value == '':
            raise ValidationError, ErrorNames.RequiredEmptyString
        return value

class MinimumLengthValidator(Validator):
    """Check that the length is larger than the minimum value."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        length = len(value)
        if self.field.min_length is not None and \
               length < self.field.min_length:
            raise ValidationError, ErrorNames.TooShort
        return value

class MaximumLengthValidator(Validator):
    """Check that the length is smaller than the maximum value."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        length = len(value)
        if self.field.max_length is not None and \
               length > self.field.max_length:
            raise ValidationError, ErrorNames.TooLong
        return value

class MinimumValueValidator(Validator):
    """Check that the value is larger than the minimum value."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        if self.field.min is not None and value < self.field.min:
            raise ValidationError, ErrorNames.TooSmall
        return value

class MaximumValueValidator(Validator):
    """Check that the value is smaller than the maximum value."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        if self.field.max is not None and value > self.field.max:
            raise ValidationError, ErrorNames.TooBig
        return value

class AllowedValuesValidator(Validator):
    """Check whether the value is in one of the allowed values."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        allowed = self.field.allowed_values
        if len(allowed) > 0 and value not in allowed:
            raise ValidationError, ErrorNames.InvalidValue
        return value

class WhitespaceValidator(Validator):
    """Check and convert the whitespaces of the value."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        option = self.field.whitespaces 
        if option in ('replace', 'collapse'):
            value = value.replace('\t', ' ')
            value = value.replace('\r', ' ')
            value = value.replace('\n', ' ')
        if option == 'collapse':
            value = ' '.join(value.split())
        if option == 'strip':
            value = value.strip()
        return value

class DecimalsValidator(Validator):
    """Check that the float value has the right precision."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        value_str = str(value)
        try:
            decimals = len(value_str.split('.')[1])
        except IndexError:
            decimals = 0
        if self.field.decimals and  decimals > self.field.decimals:
            raise ValidationError, ErrorNames.TooManyDecimals
        return value

def _flatten(list):
    out = []
    for elem in list:
        if isinstance(elem, ListTypes):
            out += _flatten(elem)
        else:
            out.append(elem)
    return out

class ListValueTypeValidator(Validator):
    """Check that the values in the value have the right type."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        if self.field.value_types:
            types = map(lambda field: field.type, self.field.value_types)
            types = tuple(_flatten(types))
            for val in value:
                if not isinstance(val, types):
                    raise ValidationError, ErrorNames.WrongContainedType
        return value

class MinimumAmountOfItemsValidator(Validator):
    """Check whether the list contains enough items."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        if self.field.min_values and value is not None and \
               len(value) < self.field.min_values:
            raise ValidationError, ErrorNames.NotEnoughElements
        return value

class MaximumAmountOfItemsValidator(Validator):
    """Check whether the list contains not too many items."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        if self.field.max_values and len(value) > self.field.max_values:
            raise ValidationError, ErrorNames.TooManyElements
        return value

class DictKeyTypeValidator(Validator):
    """Check that the values in the value have the right type."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        keys = value.keys()
        field = List(id='temp', title='temp',
                     value_types=self.field.key_types)
        validator = ListValueTypeValidator(field)
        validator.validate(keys)
        return value

class DictValueTypeValidator(Validator):
    """Check that the values in the value have the right type."""
    def validate(self, value):
        'See Schema.IValidator.IValidator'
        values = value.values()
        field = List(id='temp', title='temp',
                     value_types=self.field.value_types)
        validator = ListValueTypeValidator(field)
        validator.validate(values)
        return value

class ContainerValidator(Validator):
    """ """
    validators = [TypeValidator, RequiredValidator]

    def validate(self, value):
        'See Schema.IValidator.IValidator'        
        for validator in self.validators:
            try:
                value = validator(self.field).validate(value)
            except StopValidation:
                return value
        return value

class SingleValueValidator(ContainerValidator):
    """Validator for Single Value Fields"""
    validators = ContainerValidator.validators + [AllowedValuesValidator] 
    
class StringValidator(SingleValueValidator):
    """Completely validates a String Field."""
    validators = SingleValueValidator.validators + [StringRequiredValidator,
                                                    WhitespaceValidator,
                                                    MinimumLengthValidator,
                                                    MaximumLengthValidator]

class BooleanValidator(SingleValueValidator):
    """Completely validates a Boolean Field."""

class IntegerValidator(SingleValueValidator):
    """Completely validates a Integer Field."""
    validators = SingleValueValidator.validators + [MinimumValueValidator,
                                                    MaximumValueValidator]

class FloatValidator(SingleValueValidator):
    """Completely validates a Float Field."""
    validators = SingleValueValidator.validators + [MinimumValueValidator,
                                                    MaximumValueValidator,
                                                    DecimalsValidator]

class MultiValueValidator(ContainerValidator):
    """Validator for Single Value Fields"""
    validators = ContainerValidator.validators + [
        ListValueTypeValidator,
        MinimumAmountOfItemsValidator, MaximumAmountOfItemsValidator] 

class TupleValidator(MultiValueValidator):
    """Completely validates a Tuple Field."""

class ListValidator(TupleValidator):
    """Completely validates a List Field."""

class DictionaryValidator(MultiValueValidator):
    """Completely validates a Dictionary Field."""
    validators = ContainerValidator.validators + [
        DictKeyTypeValidator, DictValueTypeValidator,
        MinimumAmountOfItemsValidator, MaximumAmountOfItemsValidator] 



=== Zope3/lib/python/Schema/ErrorNames.py 1.2 => 1.3 ===
+##############################################################################
+#
+# Copyright (c) 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+# 
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+# 
+##############################################################################
+"""Common Schema Error Names
+
+$Id$
+"""
+WrongType = "WrongType"
+
 RequiredMissing ='RequiredMissing'
+
 RequiredEmptyString = 'RequiredEmptyString'
+
 TooBig = 'TooBig'
+
 TooSmall = 'TooSmall'
+
 TooLong = 'TooLong'
+
 TooShort = 'TooShort'
+
+InvalidValue = 'InvalidValue'
+
+TooManyDecimals = 'TooManyDecimals'
+
+WrongContainedType = "WrongContainedType"
+
+NotEnoughElements = 'NotEnoughElements'
+
+TooManyElements = 'TooManyElements'


=== Zope3/lib/python/Schema/Exceptions.py 1.3 => 1.4 ===
+##############################################################################
+#
+# Copyright (c) 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+# 
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+# 
+##############################################################################
+"""Validation Exceptions
+
+$Id$
+"""
 
 class StopValidation(Exception):
+    """This exception is raised, if the validation is done for sure early.
+    Note that this exception should be always caught, since it is just a
+    way for the validator to save time."""
     pass
 
+
 class ValidationError(Exception):
-    def __init__(self,error_name):
+    """If some check during the Validation process fails, this exception is
+    raised."""
+
+    def __init__(self, error_name):
         Exception.__init__(self)
-        self.error_name=error_name
+        self.error_name = error_name
 
-    def __cmp__(self,other):
+    def __cmp__(self, other):
         return cmp(self.error_name, other.error_name)
 
+
 class ValidationErrorsAll(Exception):
-    def __init__(self,list):
+    """This is a collection error that contains all exceptions that occured
+    during the validation process."""
+
+    def __init__(self, list):
         Exception.__init__(self)
-        self.errors = list
\ No newline at end of file
+        self.errors = list


=== Zope3/lib/python/Schema/IField.py 1.1 => 1.2 ===
-from Interface import Interface
+##############################################################################
+#
+# Copyright (c) 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+# 
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+# 
+##############################################################################
+"""These are the interfaces for the common fields.
 
+$Id$
+"""
+from Interface import Interface
 import _Field as Field
 
 class IField(Interface):
@@ -8,58 +24,74 @@
     IBoolean, requiredness settings may make no difference.
     """
 
-    title = Field.Str(
+    title = Field.String(
         title="Title",
         description="Title.",
         default=""
         )
     
-    description = Field.Str(
+    description = Field.String(
         title="Description",
         description="Description.",
         default="",
         required=0)
 
-    readonly = Field.Bool(
+    readonly = Field.Boolean(
         title="Read Only",
         description="Read-only.",
         default=0)
     
-    required = Field.Bool(
+    required = Field.Boolean(
         title="Required",
         description="Required.",
         default=1)
+
+
+class ISingleValueField(IField):
+    """This field consists always only of one value and it not a homogeneous
+    container, like a list. Note that structures and instances of classes
+    might or might not be ISingleValueFields."""
+    
+    allowed_values = Field.Tuple(
+        title="Allowed Values",
+        description="Only values specified here can be values of this field. "
+                    "If the list is empty, then there are no further "
+                    "restictions.",
+        required=0,
+        default=())
+        
+
     
-class IBool(IField):
-    default = Field.Bool(
+class IBoolean(ISingleValueField):
+    """Describes the footprint of a Boolean variable."""
+
+    default = Field.Boolean(
         title="Default",
         description="Default.",
         default=0)
 
-class IStr(IField):
 
-    default = Field.Str(
+class IString(ISingleValueField):
+    """Describes the footprint of a String variable."""
+
+    default = Field.String(
         title="Default",
         description="Default.",
         default="")
     
-    # whitespace = Field.Selection(
-    #     title="Whitespace",
-    #     description="preserve: whitespace is preserved."
-    #                 "replace: all occurences of tab, line feed and "
-    #                 "carriage return are replaced with space characters. "
-     #                 "collapse: first process as in 'replace', then "
-    #                 "collapse all spaces to a single space, and strip any "
-    #                 "spaces from front and back."
-    #                 "strip: strip off whitespace from front and back.",
-    #     items=[("preserve", "preserve"),
-    #            ("replace", "replace"),
-    #            ("collapse", "collapse"),
-    #            ("strip", "strip")],
-    #     selection_type=IStr,
-    #     default="strip")
+    whitespace = Field.String(
+        title="Whitespace",
+        description="preserve: whitespace is preserved."
+                    "replace: all occurences of tab, line feed and "
+                    "carriage return are replaced with space characters. "
+                    "collapse: first process as in 'replace', then "
+                    "collapse all spaces to a single space, and strip any "
+                    "spaces from front and back."
+                    "strip: strip off whitespace from front and back.",
+        allowed_values=("preserve", "replace", "collapse", "strip"),
+        default="strip")
 
-    min_length = Field.Int(
+    min_length = Field.Integer(
         title="Minimum length",
         description=("Value after whitespace processing cannot have less than "
                      "min_length characters. If min_length is None, there is "
@@ -68,54 +100,128 @@
         min=0, # needs to be a positive number
         default=0)
 
-    max_length = Field.Int(
+    max_length = Field.Integer(
         title="Maximum length",
         description=("Value after whitespace processing cannot have greater "
-                     "or equal than max_length characters. If max_length is None, "
-                     "there is no maximum."),
+                     "or equal than max_length characters. If max_length is "
+                     "None, there is no maximum."),
         required=0,
         min=0, # needs to be a positive number
         default=None)
 
-##     pattern = Str(
-##         title="Pattern",
-##         description="A regular expression by which the value "
-##                     "(after whitespace processing) should be constrained."
-##                     "If None, no pattern checking is performed.",
-        
-##         default=None,
-##         required=0)
     
-class IInt(IField):
-    default = Field.Int(
+class IInteger(ISingleValueField):
+    """Describes the footprint of an Integer variable."""
+
+    default = Field.Integer(
         title="Default",
         description="Default.",
         default=0)
     
-    min = Field.Int(
+    min = Field.Integer(
         title="Minimum",
-        description="Value after whitespace processing cannot have less than "
-                    "min characters. If min is None, there is no minimum.",
+        description="The minimal numerical value accepted. If min is None, "
+                    "there is no minimum.",
         required=0,
-        min=0,
         default=0)
 
-    max = Field.Int(
+    max = Field.Integer(
         title="Maximum",
-        description="Value after whitespace processing cannot have greater or "
-                    "equal than max characters. If max is None, there is no "
-                    "maximum.",
+        description="The masximal numerical value accepted. If min is None, "
+                    "there is no minimum.",
         required=0,
-        min=0,
         default=None)
+    
+    
+class IFloat(ISingleValueField):
+    """Describes the footprint of a Float variable."""
 
-##    pattern = Field.Str(
-##         title="Pattern",
-##         description="A regular expression by which the value "
-##                     "(after whitespace processing) should be constrained."
-##                     "If None, no pattern checking is performed.",
-        
-##         default=None,
-##         required=0)
+    default = Field.Float(
+        title="Default",
+        description="Default.",
+        default=0)
     
+    min = Field.Float(
+        title="Minimum",
+        description="The minimal numerical value accepted. If min is None, "
+                    "there is no minimum.",
+        required=0,
+        default=0)
+
+    max = Field.Float(
+        title="Maximum",
+        description="The masximal numerical value accepted. If min is None, "
+                    "there is no minimum.",
+        required=0,
+        default=None)
     
+    decimals = Field.Integer(
+        title="Decimal Places",
+        description="Defines the amount of decimal places the floating point "
+                    "can have. This value is also know as precision. If the "
+                    "value is None, no precision is required.",
+        required=0,
+        default=None)
+
+
+class IMultipleValueField(IField):
+    """This field will contain some sort of collection of objects whose types
+    can be often defined through a finite set of types."""
+
+    value_types = Field.Tuple(
+        title="Value Types",
+        description="Defines the value types that are allowed in the list. "
+                    "If the list is empty, then all types are allowed.",
+        required=0,
+        default=())
+
+    min_values = Field.Integer(
+        title="Minimum amount of values",
+        description="The minimum amount of values in the list. If min_values "
+                    "is None, there is no minimum.",
+        min=0,
+        required=0,
+        default=0)
+
+    max_values = Field.Integer(
+        title="Maximum amount of values",
+        description="The maximum amount of values in the list. If max_values "
+                    "is None, there is no maximum.",
+        min=0,
+        required=0,
+        default=None)
+
+
+class ITuple(IMultipleValueField):
+    """Describes the footprint of a Tuple variable."""
+
+    default = Field.Tuple(
+        title="Default",
+        description="Default.",
+        default=())    
+
+
+class IList(ITuple):
+    """Describes the footprint of a List variable."""
+
+    default = Field.List(
+        title="Default",
+        description="Default.",
+        default=[])
+
+
+class IDictionary(IMultipleValueField):
+    """Describes the footprint of a Dictionary variable."""
+
+    default = Field.Dictionary(
+        title="Default",
+        description="Default.",
+        default={})    
+
+    key_types = Field.Tuple(
+        title="Value Types",
+        description="Defines the key types that are allowed in the "
+                    "dictionary. If the list is empty, then all types "
+                    "are allowed.",
+        required=0,
+        default=())


=== Zope3/lib/python/Schema/_Field.py 1.3 => 1.4 ===
+##############################################################################
+#
+# Copyright (c) 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+# 
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+# 
+##############################################################################
+"""
+$Id$
+"""
 from Interface.Attribute import Attribute
 from Interface.Implements import objectImplements
 
 from Exceptions import StopValidation, ValidationError
 import ErrorNames
-#from _Schema import validate
 
-class Field(Attribute):
 
+class Field(Attribute):
     # we don't implement the same interface Attribute
     __implements__ = ()
-
+    type = None
     default = None
     required = 0
 
     def __init__(self, **kw):
-        """
-        Pass in field values as keyword parameters.
-        """
+        """Pass in field values as keyword parameters."""
         for key, value in kw.items():
             setattr(self, key, value)
         super(Field, self).__init__(self.title or 'no title')
 
     def validate(self, value):
         try:
-            self._validate(value)
+            return self.validator(self).validate(value)
         except StopValidation:
-            pass
-
-    def _validate(self, value):
-        if value is None:
-            if self.required:
-                raise ValidationError, ErrorNames.RequiredMissing
-            else:
-                # we are done with validation for sure
-                raise StopValidation
-
-class Str(Field):
+            return value
 
+class SingleValueField(Field):
+    """A field that contains only one value."""
+    allowed_values = []
+
+class String(SingleValueField):
+    """A field representing a String."""
+    type = str
     min_length = None
     max_length = None
+    whitespaces = "preserve"
 
-    def _validate(self, value):
-        super(Str, self)._validate(value)
-        if self.required and value == '':
-            raise ValidationError,ErrorNames.RequiredEmptyString
-        length = len(value)
-
-        if self.min_length is not None and length < self.min_length:
-            raise ValidationError, ErrorNames.TooShort
-        if self.max_length is not None and length > self.max_length:
-            raise ValidationError, ErrorNames.TooLong
-
-class Bool(Field):
-
-    def _validate(self, value):
-        super(Bool, self)._validate(value)
-
-class Int(Field):
+class Boolean(SingleValueField):
+    """A field representing a Boolean."""
+    type = type(not 1) 
+
+class Integer(SingleValueField):
+    """A field representing a Integer."""
+    type = int
+    min = max = None
 
+class Float(SingleValueField):
+    """A field representing a Floating Point."""
+    type = float, int
     min = max = None
+    decimals = None
+
+class Tuple(Field):
+    """A field representing a Tuple."""
+    type = tuple
+    value_types = None
+    min_values = max_values = None
+
+class List(Field):
+    """A field representing a List."""
+    type = list
+    value_types = None
+    min_values = max_values = None
+
+class Dictionary(Field):
+    """A field representing a Dictionary."""
+    type = dict
+    min_values = max_values = None
+    key_types = value_types = None
 
-    def _validate(self, value):
-        super(Int, self)._validate(value)
-        if self.min is not None and value < self.min:
-            raise ValidationError, ErrorNames.TooSmall
-        if self.max is not None and value > self.max:
-            raise ValidationError, ErrorNames.TooBig
 


=== Zope3/lib/python/Schema/_Schema.py 1.3 => 1.4 ===
-from Schema.Exceptions import StopValidation, ValidationError, ValidationErrorsAll
+##############################################################################
+#
+# Copyright (c) 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+# 
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+# 
+##############################################################################
+"""
+$Id$
+"""
+from Interface import Interface
+import Validator
+from Schema.Exceptions import \
+     StopValidation, ValidationError, ValidationErrorsAll
+
+
+class Schema(Interface):
+    """This is really just a marker class, but it seems more userfriendly
+    this way."""
+    
 
 def validateMapping(schema, values):
     """Pass in field values in mapping and validate whether they
@@ -9,13 +34,13 @@
         attr = schema.getDescriptionFor(name)
         if IField.isImplementedBy(attr):
             attr.validate(values.get(name))
-
+    return 1
 
 def validateMappingAll(schema, values):
     """Pass in field values in mapping and validate whether they
     conform to schema.
     """
-    list=[]
+    list = []
     from IField import IField
     for name in schema.names(1):
         attr = schema.getDescriptionFor(name)
@@ -26,27 +51,51 @@
                 list.append((name, e))
     if list:
         raise ValidationErrorsAll, list
+    return 1
 
 # Now we can create the interesting interfaces and wire them up:
 def wire():
-
     from Interface.Implements import implements
 
     from IField import IField
     from _Field import Field
     implements(Field, IField, 0)
+    Field.validator = Validator.RequiredValidator
 
-    from IField import IBool
-    from _Field import Bool
-    implements(Bool, IBool, 0)
-
-    from IField import IStr
-    from _Field import Str
-    implements(Str, IStr, 0)
-
-    from IField import IInt
-    from _Field import Int
-    implements(Int, IInt, 0)
+    from IField import IBoolean
+    from _Field import Boolean
+    implements(Boolean, IBoolean, 0)
+    Boolean.validator = Validator.BooleanValidator
+
+    from IField import IString
+    from _Field import String
+    implements(String, IString, 0)
+    String.validator = Validator.StringValidator
+
+    from IField import IInteger
+    from _Field import Integer
+    implements(Integer, IInteger, 0)
+    Integer.validator = Validator.IntegerValidator
+
+    from IField import IFloat
+    from _Field import Float
+    implements(Float, IFloat, 0)
+    Float.validator = Validator.FloatValidator
+
+    from IField import ITuple
+    from _Field import Tuple
+    implements(Tuple, ITuple, 0)
+    Tuple.validator = Validator.TupleValidator
+
+    from IField import IList
+    from _Field import List
+    implements(List, IList, 0)
+    List.validator = Validator.ListValidator
+
+    from IField import IDictionary
+    from _Field import Dictionary
+    implements(Dictionary, IDictionary, 0)
+    Dictionary.validator = Validator.DictionaryValidator
 
 
 wire()


=== Zope3/lib/python/Schema/__init__.py 1.1 => 1.2 ===
-from _Field import Field, Int, Bool, Str
+##############################################################################
+#
+# Copyright (c) 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+# 
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+# 
+##############################################################################
+"""Schema package constructor
+
+$Id$
+"""
+from _Field import *
+from _Schema import Schema, validateMapping, validateMappingAll