[Zope3-checkins] CVS: Zope3/src/zope/schema - fields.txt:1.1 __init__.py:1.19 _field.py:1.34 interfaces.py:1.45 vocabulary.py:1.23

Gary Poster gary at zope.com
Thu May 6 12:14:21 EDT 2004


Update of /cvs-repository/Zope3/src/zope/schema
In directory cvs.zope.org:/tmp/cvs-serv9758/src/zope/schema

Modified Files:
	__init__.py _field.py interfaces.py vocabulary.py 
Added Files:
	fields.txt 
Log Message:
Convert the field collection behavior as described in 
http://mail.zope.org/pipermail/zope3-dev/2004-May/010797.html

The Sequence field is removed.  As I spoke with Stephan, it may be acceptable to add the Sequence field back in if it actually means something.  Sequence did mean it was iterable but container access API was not described.  It should be described.  IPythonSequence might describe this API.  A Sequence widget should require specification of the factory.

Set now specifies a sets.Set.

IChoiceSequence was removed.




=== Added File Zope3/src/zope/schema/fields.txt ===
======
Fields
======

This document highlights unusual and subtle aspects of various fields and
field classes, and is not intended to be a general introduction to schema
fields.  Please see README.txt for a more general introduction.

While many field types, such as Int, TextLine, Text, and Bool are relatively
straightforward, a few have some subtlety.  We will explore the general
class of collections and discuss how to create a custom creation field; discuss
Choice fields, vocabularies, and their use with collections; and close with a
look at the standard zope.app approach to using these fields to find views
("widgets").

Collections
===========

Normal fields typically describe the API of the attribute--does it behave as a
Python Int, or a Float, or a Bool--and various constraints to the model, such
as a maximum or minimum value.  Collection fields have additional requirements
because they contain other types, which may also be described and constrained.

For instance, imagine a list that contains non-negative floats and enforces
uniqueness, In a schema, this might be written as follows::

  >>> from zope.interface import Interface
  >>> from zope.schema import List, Float
  >>> class IInventoryItem(Interface):
  ...     pricePoints = List(
  ...         Float(title=u"Price", min=0),
  ...         unique=True, title=u"Price Points")

This indicates several things.

- pricePoints is an attribute of objects that implement IInventoryItem.
- The contents of pricePoints can be accessed and manipulated via a Python list
  API.
- Each member of pricePoints must be a non-negative float.
- Members cannot be duplicated within pricePoints: each must be must be unique.
- The attribute and its contents have descriptive titles.  Typically these
  would be message ids.

This declaration creates a field that implements a number of interfaces, among
them these::

  >>> from zope.schema.interfaces import IList, ISequence, ICollection
  >>> IList.providedBy(IInventoryItem.pricePoints)
  True
  >>> ISequence.providedBy(IInventoryItem.pricePoints)
  True
  >>> ICollection.providedBy(IInventoryItem.pricePoints)
  True

Creating a custom collection field
----------------------------------

Ideally, custom collection fields have interfaces that inherit appropriately
from either zope.schema.interfaces.ISequence or
zope.schema.interfaces.IUnorderedCollection.  Most collection fields should be
able to subclass zope.schema._field.AbstractCollection to get the necessary
behavior.  Notice the behavior of the Set field in zope.schema._field: this
would also be necessary to implement a Bag.

Choices and Vocabularies
========================

Choice fields are the schema way of spelling enumerated fields and more.  By
providing a dynamically generated vocabulary, the choices available to a
choice field can be contextually calculated.  

Simple choices do not have to explicitly use vocabularies::

  >>> from zope.schema import Choice
  >>> f = Choice((640, 1028, 1600))
  >>> f.validate(640)
  >>> f.validate(960)
  Traceback (most recent call last):
  ...
  ConstraintNotSatisfied: 960
  >>> f.validate('bing')
  Traceback (most recent call last):
  ...
  ConstraintNotSatisfied: bing

More complex choices will want to use registered vocabularies.  Vocabularies
have a simple interface, as defined in
zope.schema.interfaces.IBaseVocabulary.  A vocabulary must minimally be able
to determine whether it contains a value, to create a term object for a value,
and to return a query interface (or None) to find items in itself.  Term
objects are an abstraction that wraps a vocabulary value.  

The Zope application server typically needs a fuller interface that provides
"tokens" on its terms: ASCII values that have a one-to-one relationship to the
values when the vocabulary is asked to "getTermByToken".  If a vocabulary is
small, it can also support the IIterableVocabulary interface.

If a vocabulary has been registered, then the choice merely needs to pass the
vocabulary identifier to the "vocabulary" argument of the choice during
instantiation.

A start to a vocabulary implementation that may do all you need for many simple
tasks may be found in zope.schema.vocabulary.SimpleVocabulary.  Because
registered vocabularies are simply callables passed a context, many
registered vocabularies can simply be functions that rely on SimpleVocabulary::

  >>> from zope.schema.vocabulary import SimpleVocabulary
  >>> def myDynamicVocabulary(context):
  ...     v = dynamic_context_calculation_that_returns_an_iterable(context)
  ...     return SimpleVocabulary.fromValues(v)
  ... 

The vocabulary interface is simple enough that writing a custom vocabulary is
not too difficult itself.

Choices and Collections
-----------------------

Choices are a field type and can be used as a value_type for collections.  Just
as a collection of an "Int" value_type constrains members to integers, so a
choice-based value type constrains members to choices within the Choice's
vocabulary.  Typically in the Zope application server widgets are found not
only for the collection and the choice field but also for the vocabulary on
which the choice is based.

Using Choice and Collection Fields within a Widget Framework
============================================================

While fields support several use cases, including code documentation and data
decription and even casting, a significant use case influencing their design is
to support form generation--generating widgets for a field.  Choice and
collection fields are expected to be used within widget frameworks.  The
zope.app approach typically (but configurably) uses multiple dispatches to 
find widgets on the basis of various aspects of the fields.

Widgets for all fields are found by looking up a browser view of the field
providing an input or display widget view.  Typically there is only a single
"widget" registered for Choice fields.  When it is looked up, it performs
another dispatch--another lookup--for a widget registered for both the field
and the vocabulary.  This widget typically has enough information to render
without a third dispatch.

Collection fields may fire several dispatches.  The first is the usual lookup
by field.  A single "widget" should be registered for ICollection, which does
a second lookup by field and value_type constraint, if any, or, theoretically,
if value_type is None, renders some absolutely generic collection widget that
allows input of any value imaginable: a check-in of such a widget would be
unexpected.  This second lookup may find a widget that knows how to render,
and stop.  However, the value_type may be a choice, which will usually fire a
third dispatch: a search for a browser widget for the collection field, the
value_type field, and the vocabulary.  Further lookups may even be configured
on the basis of uniqueness and other constraints.

This level of indirection may be unnecessary for some applications, and can be
disabled with simple zcml changes within zope.app.


=== Zope3/src/zope/schema/__init__.py 1.18 => 1.19 ===
--- Zope3/src/zope/schema/__init__.py:1.18	Sat Apr 24 19:20:37 2004
+++ Zope3/src/zope/schema/__init__.py	Thu May  6 12:13:50 2004
@@ -16,7 +16,7 @@
 $Id$
 """
 from zope.schema._field import Field, Container, Iterable, Orderable
-from zope.schema._field import MinMaxLen, Sequence, Choice
+from zope.schema._field import MinMaxLen, Choice
 from zope.schema._field import Bytes, ASCII, BytesLine
 from zope.schema._field import Text, TextLine, Bool, Int, Float
 from zope.schema._field import Tuple, List, Set


=== Zope3/src/zope/schema/_field.py 1.33 => 1.34 ===
--- Zope3/src/zope/schema/_field.py:1.33	Sat Apr 24 19:20:46 2004
+++ Zope3/src/zope/schema/_field.py	Thu May  6 12:13:50 2004
@@ -19,6 +19,7 @@
 import warnings
 import re
 from datetime import datetime, date
+from sets import Set as SetType
 
 from zope.interface import classImplements, implements, directlyProvides
 from zope.interface.interfaces import IInterface, IMethod
@@ -29,8 +30,7 @@
 from zope.schema.interfaces import IInterfaceField
 from zope.schema.interfaces import IBytes, IASCII, IBytesLine
 from zope.schema.interfaces import IBool, IInt, IFloat, IDatetime
-from zope.schema.interfaces import IChoice, IChoiceSequence
-from zope.schema.interfaces import ISequence, ITuple, IList, ISet, IDict
+from zope.schema.interfaces import IChoice, ITuple, IList, ISet, IDict
 from zope.schema.interfaces import IPassword, IObject, IDate
 from zope.schema.interfaces import IURI, IId, IFromUnicode
 from zope.schema.interfaces import IVocabulary
@@ -180,25 +180,23 @@
         assert not (values is None and vocabulary is None), \
                "You must specify either values or vocabulary."
         assert values is None or vocabulary is None, \
-               "You cannot specify both, values and vocabulary."
+               "You cannot specify both values and vocabulary."
         
         self.vocabulary = None
         self.vocabularyName = None
-
         if values is not None:
-            terms = [SimpleTerm(value) for value in values]
-            self.vocabulary = SimpleVocabulary(terms)
+            self.vocabulary = SimpleVocabulary.fromValues(values)
         elif isinstance(vocabulary, (unicode, str)):
             self.vocabularyName = vocabulary
         else:
             assert IVocabulary.providedBy(vocabulary)
             self.vocabulary = vocabulary
-
         # Before a default value is checked, it is validated. However, a
-        # vocabulary is usually not complete when these fields are
-        # initialized. Therefore signalize to the validation method to ignore
-        # default value checks during initialization.
-        self._init_field = True
+        # named vocabulary is usually not complete when these fields are
+        # initialized. Therefore signal the validation method to ignore
+        # default value checks during initialization of a Choice tied to a
+        # registered vocabulary.
+        self._init_field = bool(self.vocabularyName)
         super(Choice, self).__init__(**kw)
         self._init_field = False
 
@@ -230,22 +228,17 @@
         # Pass all validations during initialization
         if self._init_field:
             return
-
         super(Choice, self)._validate(value)
-
         vocabulary = self.vocabulary
-        
         if vocabulary is None:
             vr = getVocabularyRegistry()
             try:
                 vocabulary = vr.get(None, self.vocabularyName)
             except VocabularyRegistryError:
-                raise ValueError("can't validate value without vocabulary")
-
+                raise ValueError("Can't validate value without vocabulary")
         if value not in vocabulary:
             raise ConstraintNotSatisfied, value
 
-
 class InterfaceField(Field):
     __doc__ = IInterfaceField.__doc__
     implements(IInterfaceField)
@@ -287,55 +280,53 @@
 
         temp_values.append(item)
 
-
-class Sequence(MinMaxLen, Iterable, Field):
-    __doc__ = ISequence.__doc__
-    implements(ISequence)
+class AbstractCollection(MinMaxLen, Iterable, Field):
     value_type = None
 
     def __init__(self, value_type=None, unique=False, **kw):
-        super(Sequence, self).__init__(**kw)
+        super(AbstractCollection, self).__init__(**kw)
         # whine if value_type is not a field
         if value_type is not None and not IField.providedBy(value_type):
             raise ValueError, "'value_type' must be field instance."
         self.value_type = value_type
-        # When a choice is used for the sequence, signalize this through an
-        # interface, so that special views can be provided. 
-        if IChoice.providedBy(value_type):
-            directlyProvides(self, IChoiceSequence)
         self.unique = unique
 
     def bind(self, object):
         """See zope.schema._bootstrapinterfaces.IField."""
-        clone = super(Sequence, self).bind(object)
-        # We need to bin the choice as well, so the vocabulary is generated.
-        if IChoiceSequence.providedBy(self):
+        clone = super(AbstractCollection, self).bind(object)
+        # binding value_type is necessary for choices with named vocabularies,
+        # and possibly also for other fields.
+        if clone.value_type is not None:
            clone.value_type = clone.value_type.bind(object) 
         return clone
 
     def _validate(self, value):
-        super(Sequence, self)._validate(value)
+        super(AbstractCollection, self)._validate(value)
         errors = _validate_sequence(self.value_type, value)
         if errors:
             raise WrongContainedType, errors
-
         if self.unique:
             _validate_uniqueness(value)
 
-class Tuple(Sequence):
+class Tuple(AbstractCollection):
     """A field representing a Tuple."""
     implements(ITuple)
     _type = tuple
 
-class List(Sequence):
+class List(AbstractCollection):
     """A field representing a List."""
     implements(IList)
     _type = list
 
-class Set(Sequence):
+class Set(AbstractCollection):
     """A field representing a set."""
     implements(ISet)
-
+    _type = SetType
+    def __init__(self, **kw):
+        if 'unique' in kw: # set members are always unique
+            raise TypeError(
+                "__init__() got an unexpected keyword argument 'unique'")
+        super(Set, self).__init__(unique=True, **kw)
 
 def _validate_fields(schema, value, errors=None):
     if errors is None:


=== Zope3/src/zope/schema/interfaces.py 1.44 => 1.45 ===
--- Zope3/src/zope/schema/interfaces.py:1.44	Sat Apr 24 19:20:54 2004
+++ Zope3/src/zope/schema/interfaces.py	Thu May  6 12:13:50 2004
@@ -370,8 +370,12 @@
          "IVocabularyRegistry should be used to locate an appropriate\n"
          "IBaseVocabulary object."))
 
-class ISequence(IMinMaxLen, IIterable, IContainer):
-    u"""Field containing a Sequence value.
+# Collections:
+
+# Abstract
+
+class ICollection(IMinMaxLen, IIterable, IContainer):
+    u"""Abstract interface containing a collection value.
 
     The Value must be iterable and may have a min_length/max_length.
     """
@@ -382,29 +386,34 @@
                         u"expressed via a Field."))
 
     unique = Bool(
-        title = _('Unique Values'),
-        description = _('Specifies whether the values of the sequence must be'
-                        'unique.'),
+        title = _('Unique Members'),
+        description = _('Specifies whether the members of the collection '
+                        'must be unique.'),
         default=False)
 
-class IChoiceSequence(Interface):
-    u"""Marker interface to signalize sequences whose value_type is a Choice.
+class ISequence(ICollection):
+    u"""Abstract interface specifying that the value is ordered"""
+
+class IUnorderedCollection(ICollection):
+    u"""Abstract interface specifying that the value cannot be ordered"""
+
+# Concrete
 
-    This will simplify the selection of specialized views (i.e. widgets).
-    """
-    
 class ITuple(ISequence):
-    u"""Field containing a conventional tuple."""
+    u"""Field containing a value that implements the API of a conventional 
+    Python tuple."""
 
 class IList(ISequence):
-    u"""Field containing a conventional list."""
+    u"""Field containing a value that implements the API of a conventional 
+    Python list."""
 
-class ISet(ISequence):
-    u"""Field representing an unordered collection of values from a
-    vocabulary.
+class ISet(IUnorderedCollection):
+    u"""Field containing a value that implements the API of a conventional 
+    Python standard library sets.Set."""
+    
+    unique = Attribute(u"This ICollection interface attribute must be True")
 
-    Specific values may be represented at most once.
-    """
+# (end Collections)
 
 class IObject(IField):
     u"""Field containing an Object value."""
@@ -469,6 +478,10 @@
         Control characters are not allowed.
         """)
 
+class ITitledTokenizedTerm(ITokenizedTerm):
+    """A tokenized term that includes a title."""
+    
+    title = TextLine(title=_(u"Title"))
 
 class IBaseVocabulary(Interface):
     """Representation of a vocabulary.


=== Zope3/src/zope/schema/vocabulary.py 1.22 => 1.23 ===
--- Zope3/src/zope/schema/vocabulary.py:1.22	Sat Apr 24 19:20:57 2004
+++ Zope3/src/zope/schema/vocabulary.py	Thu May  6 12:13:50 2004
@@ -19,23 +19,29 @@
 from zope.schema.interfaces import ValidationError
 from zope.schema.interfaces import IVocabularyRegistry
 from zope.schema.interfaces import IVocabulary, IVocabularyTokenized
-from zope.schema.interfaces import ITokenizedTerm
+from zope.schema.interfaces import ITokenizedTerm, ITitledTokenizedTerm
 
 # simple vocabularies performing enumerated-like tasks
 
+_marker = object()
+
 class SimpleTerm(object):
     """Simple tokenized term used by SimpleVocabulary."""
 
     implements(ITokenizedTerm)
 
-    def __init__(self, value, token=None):
+    def __init__(self, value, token=None, title=None):
         """Create a term for value and token. If token is omitted,
-        str(value) is used for the token
+        str(value) is used for the token.  If title is provided, 
+        term implements ITitledTokenizedTerm.
         """
         self.value = value
         if token is None:
             token = value
         self.token = str(token)
+        self.title = title
+        if title is not None:
+            directlyProvides(self, ITitledTokenizedTerm)
 
 class SimpleVocabulary(object):
     """Vocabulary that works from a sequence of terms."""
@@ -72,7 +78,7 @@
         One or more interfaces may also be provided so that alternate
         widgets may be bound without subclassing.
         """
-        terms = [cls.createTerm((value, token)) for (token, value) in items]
+        terms = [cls.createTerm(value, token) for (token, value) in items]
         return cls(terms, *interfaces)
     fromItems = classmethod(fromItems)
 
@@ -92,16 +98,13 @@
         return cls(terms, *interfaces)
     fromValues = classmethod(fromValues)
 
-    def createTerm(cls, data):
+    def createTerm(cls, *args):
         """Create a single term from data.
 
         Subclasses may override this with a class method that creates
-        a term of the appropriate type from the single data argument.
+        a term of the appropriate type from the arguments.
         """
-        if isinstance(data, tuple):
-            return SimpleTerm(*data)
-        else:
-            return SimpleTerm(data)
+        return SimpleTerm(*args)
     createTerm = classmethod(createTerm)
 
     def __contains__(self, value):




More information about the Zope3-Checkins mailing list