API¶
This document describes the low-level API of the interfaces and classes provided by this package. The narrative documentation is a better guide to the intended usage.
Interfaces¶
-
interface
zope.schema.interfaces.IField[source]¶ Extends:
zope.schema._bootstrapinterfaces.IValidatableBasic Schema Field Interface.
Fields are used for Interface specifications. They at least provide a title, description and a default value. You can also specify if they are required and/or readonly.
The Field Interface is also used for validation and specifying constraints.
We want to make it possible for a IField to not only work on its value but also on the object this value is bound to. This enables a Field implementation to perform validation against an object which also marks a certain place.
Note that many fields need information about the object containing a field. For example, when validating a value to be set as an object attribute, it may be necessary for the field to introspect the object’s state. This means that the field needs to have access to the object when performing validation:
bound = field.bind(object) bound.validate(value)
-
bind(object)¶ Return a copy of this field which is bound to context.
The copy of the Field will have the ‘context’ attribute set to ‘object’. This way a Field can implement more complex checks involving the object’s location/environment.
Many fields don’t need to be bound. Only fields that condition validation or properties on an object containing the field need to be bound.
-
title¶ Title
A short summary or label
Implementation: zope.schema.TextLineRead Only: False Required: False Default Value: u’’ Allowed Type: unicode
-
description¶ Description
A description of the field
Implementation: zope.schema.TextRead Only: False Required: False Default Value: u’’ Allowed Type: unicode
-
required¶ Required
Tells whether a field requires its value to exist.
Implementation: zope.schema.BoolRead Only: False Required: True Default Value: True Allowed Type: bool
-
readonly¶ Read Only
If true, the field’s value cannot be changed.
Implementation: zope.schema.BoolRead Only: False Required: False Default Value: False Allowed Type: bool
-
default¶ Default Value
The field default value may be None or a legal field value
Implementation: zope.schema.FieldRead Only: False Required: True Default Value: None
-
missing_value¶ Missing Value
If input for this Field is missing, and that’s ok, then this is the value to use
Implementation: zope.schema.FieldRead Only: False Required: True Default Value: None
-
order¶ Field Order
The order attribute can be used to determine the order in which fields in a schema were defined. If one field is created after another (in the same thread), its order will be greater.
(Fields in separate threads could have the same order.)
Implementation: zope.schema.IntRead Only: True Required: True Default Value: None Allowed Type: int,long
-
constraint(value)¶ Check a customized constraint on the value.
You can implement this method with your Field to require a certain constraint. This relaxes the need to inherit/subclass a Field you to add a simple constraint. Returns true if the given value is within the Field’s constraint.
-
validate(value)¶ Validate that the given value is a valid field value.
Returns nothing but raises an error if the value is invalid. It checks everything specific to a Field and also checks with the additional constraint.
-
get(object)¶ Get the value of the field for the given object.
-
query(object, default=None)¶ Query the value of the field for the given object.
Return the default if the value hasn’t been set.
-
set(object, value)¶ Set the value of the field for the object
Raises a type error if the field is a read-only field.
-
-
interface
zope.schema.interfaces.IChoice[source]¶ Extends:
zope.schema.interfaces.IFieldField whose value is contained in a predefined set
Only one, values or vocabulary, may be specified for a given choice.
-
vocabulary¶ Vocabulary or source providing values
The ISource, IContextSourceBinder or IBaseVocabulary object that provides values for this field.
Implementation: zope.schema.FieldRead Only: False Required: False Default Value: None
-
vocabularyName¶ Vocabulary name
Vocabulary name to lookup in the vocabulary registry
Implementation: zope.schema.TextLineRead Only: False Required: False Default Value: None Allowed Type: unicode
-
-
interface
zope.schema.interfaces.IContextAwareDefaultFactory[source]¶ A default factory that requires a context.
The context is the field context. If the field is not bound, context may be
None.-
__call__(context)¶ Returns a default value for the field.
-
-
interface
zope.schema.interfaces.IOrderable[source]¶ Extends:
zope.schema.interfaces.IFieldField requiring its value to be orderable.
The set of value needs support a complete ordering; the implementation mechanism is not constrained. Either
__cmp__()or ‘rich comparison’ methods may be used.
-
interface
zope.schema.interfaces.ILen[source]¶ Extends:
zope.schema.interfaces.IFieldA Field requiring its value to have a length.
The value needs to have a conventional __len__ method.
-
interface
zope.schema.interfaces.IMinMax[source]¶ Extends:
zope.schema.interfaces.IOrderableField requiring its value to be between min and max.
This implies that the value needs to support the IOrderable interface.
-
min¶ Start of the range
Implementation: zope.schema.FieldRead Only: False Required: False Default Value: None
-
max¶ End of the range (including the value itself)
Implementation: zope.schema.FieldRead Only: False Required: False Default Value: None
-
-
interface
zope.schema.interfaces.IMinMaxLen[source]¶ Extends:
zope.schema.interfaces.ILenField requiring the length of its value to be within a range
-
min_length¶ Minimum length
Value after whitespace processing cannot have less than
min_lengthcharacters (if a string type) or elements (if another sequence type). Ifmin_lengthisNone, there is no minimum.Implementation: zope.schema.IntRead Only: False Required: False Default Value: 0 Allowed Type: int,long
-
max_length¶ Maximum length
Value after whitespace processing cannot have greater or equal than
max_lengthcharacters (if a string type) or elements (if another sequence type). Ifmax_lengthisNone, there is no maximum.Implementation: zope.schema.IntRead Only: False Required: False Default Value: None Allowed Type: int,long
-
-
interface
zope.schema.interfaces.IInterfaceField[source]¶ Extends:
zope.schema.interfaces.IFieldFields with a value that is an interface (implementing zope.interface.Interface).
-
interface
zope.schema.interfaces.IBool[source]¶ Extends:
zope.schema.interfaces.IFieldBoolean Field.
-
default¶ Default Value
The field default value may be None or a legal field value
Implementation: zope.schema.BoolRead Only: False Required: True Default Value: None Allowed Type: bool
-
required¶ Required
Tells whether a field requires its value to exist.
Implementation: zope.schema.BoolRead Only: False Required: False Default Value: False Allowed Type: bool
-
-
interface
zope.schema.interfaces.IObject[source]¶ Extends:
zope.schema.interfaces.IFieldField containing an Object value.
Changed in version 4.6.0: Add the validate_invariants attribute.
-
schema¶ The Interface that defines the Fields comprising the Object.
Implementation: zope.schema.ObjectRead Only: False Required: True Default Value: None Must Provide: zope.interface.interfaces.IInterface
-
validate_invariants¶ Validate Invariants
A boolean that says whether
schema.validateInvariantsis called fromself.validate(). The default is true.Implementation: zope.schema.BoolRead Only: False Required: True Default Value: True Allowed Type: bool
-
Conversions¶
Strings¶
-
interface
zope.schema.interfaces.IBytes[source]¶ Extends:
zope.schema.interfaces.IMinMaxLen,zope.schema.interfaces.IIterable,zope.schema.interfaces.IFieldField containing a byte string (like the python str).
The value might be constrained to be with length limits.
-
interface
zope.schema.interfaces.IBytesLine[source]¶ Extends:
zope.schema.interfaces.IBytesField containing a byte string without newlines.
-
interface
zope.schema.interfaces.IText[source]¶ Extends:
zope.schema.interfaces.IMinMaxLen,zope.schema.interfaces.IIterable,zope.schema.interfaces.IFieldField containing a unicode string.
-
interface
zope.schema.interfaces.ITextLine[source]¶ Extends:
zope.schema.interfaces.ITextField containing a unicode string without newlines.
-
interface
zope.schema.interfaces.IASCII[source]¶ Extends:
zope.schema.interfaces.INativeStringField containing a 7-bit ASCII string. No characters > DEL (chr(127)) are allowed
The value might be constrained to be with length limits.
-
interface
zope.schema.interfaces.IASCIILine[source]¶ Extends:
zope.schema.interfaces.IASCIIField containing a 7-bit ASCII string without newlines.
-
interface
zope.schema.interfaces.INativeString[source]¶ Extends:
zope.schema.interfaces.IBytesA field that always contains the native
strtype.
-
interface
zope.schema.interfaces.INativeStringLine[source]¶ Extends:
zope.schema.interfaces.IBytesLineA field that always contains the native
strtype, without any newlines.Changed in version 4.9.0: This is now a distinct type instead of an alias for either
ITextLineorIBytesLine, depending on the platform.
-
interface
zope.schema.interfaces.IPassword[source]¶ Extends:
zope.schema.interfaces.ITextLineField containing a unicode password string without newlines.
-
interface
zope.schema.interfaces.IURI[source]¶ Extends:
zope.schema.interfaces.INativeStringLineA field containing an absolute URI
-
interface
zope.schema.interfaces.IId[source]¶ Extends:
zope.schema.interfaces.INativeStringLineA field containing a unique identifier
A unique identifier is either an absolute URI or a dotted name. If it’s a dotted name, it should have a module/package name as a prefix.
-
interface
zope.schema.interfaces.IPythonIdentifier[source]¶ Extends:
zope.schema.interfaces.INativeStringLineA single Python identifier, such as a variable name.
New in version 4.9.0.
-
interface
zope.schema.interfaces.IDottedName[source]¶ Extends:
zope.schema.interfaces.INativeStringLineDotted name field.
Values of DottedName fields must be Python-style dotted names.
-
min_dots¶ Minimum number of dots
Implementation: zope.schema.IntRead Only: False Required: True Default Value: 0 Allowed Type: int,long
-
max_dots¶ Maximum number of dots (should not be less than min_dots)
Implementation: zope.schema.IntRead Only: False Required: False Default Value: None Allowed Type: int,long
-
Numbers¶
-
interface
zope.schema.interfaces.INumber[source]¶ Extends:
zope.schema.interfaces.IMinMax,zope.schema.interfaces.IFieldField containing a generic number:
numbers.Number.See also
New in version 4.6.0.
-
min¶ Start of the range
Implementation: zope.schema.NumberRead Only: False Required: False Default Value: None Allowed Type: numbers.Number
-
max¶ End of the range (including the value itself)
Implementation: zope.schema.NumberRead Only: False Required: False Default Value: None Allowed Type: numbers.Number
-
default¶ Default Value
The field default value may be None or a legal field value
Implementation: zope.schema.NumberRead Only: False Required: True Default Value: None Allowed Type: numbers.Number
-
-
interface
zope.schema.interfaces.IComplex[source]¶ Extends:
zope.schema.interfaces.INumberField containing a complex number:
numbers.Complex.See also
New in version 4.6.0.
-
min¶ Start of the range
Implementation: zope.schema.ComplexRead Only: False Required: False Default Value: None Allowed Type: numbers.Complex
-
max¶ End of the range (including the value itself)
Implementation: zope.schema.ComplexRead Only: False Required: False Default Value: None Allowed Type: numbers.Complex
-
default¶ Default Value
The field default value may be None or a legal field value
Implementation: zope.schema.ComplexRead Only: False Required: True Default Value: None Allowed Type: numbers.Complex
-
-
interface
zope.schema.interfaces.IReal[source]¶ Extends:
zope.schema.interfaces.IComplexField containing a real number:
numbers.IReal.See also
New in version 4.6.0.
-
min¶ Start of the range
Implementation: zope.schema.RealRead Only: False Required: False Default Value: None Allowed Type: numbers.Real
-
max¶ End of the range (including the value itself)
Implementation: zope.schema.RealRead Only: False Required: False Default Value: None Allowed Type: numbers.Real
-
default¶ Default Value
The field default value may be None or a legal field value
Implementation: zope.schema.RealRead Only: False Required: True Default Value: None Allowed Type: numbers.Real
-
-
interface
zope.schema.interfaces.IRational[source]¶ Extends:
zope.schema.interfaces.IRealField containing a rational number:
numbers.IRational.See also
New in version 4.6.0.
-
min¶ Start of the range
Implementation: zope.schema.RationalRead Only: False Required: False Default Value: None Allowed Type: numbers.Rational
-
max¶ End of the range (including the value itself)
Implementation: zope.schema.RationalRead Only: False Required: False Default Value: None Allowed Type: numbers.Rational
-
default¶ Default Value
The field default value may be None or a legal field value
Implementation: zope.schema.RationalRead Only: False Required: True Default Value: None Allowed Type: numbers.Rational
-
-
interface
zope.schema.interfaces.IIntegral[source]¶ Extends:
zope.schema.interfaces.IRationalField containing an integral number: class:
numbers.Integral.See also
New in version 4.6.0.
-
min¶ Start of the range
Implementation: zope.schema.IntegralRead Only: False Required: False Default Value: None Allowed Type: numbers.Integral
-
max¶ End of the range (including the value itself)
Implementation: zope.schema.IntegralRead Only: False Required: False Default Value: None Allowed Type: numbers.Integral
-
default¶ Default Value
The field default value may be None or a legal field value
Implementation: zope.schema.IntegralRead Only: False Required: True Default Value: None Allowed Type: numbers.Integral
-
-
interface
zope.schema.interfaces.IInt[source]¶ Extends:
zope.schema.interfaces.IIntegralField containing exactly the native class
int(or, on Python 2,long).See also
-
min¶ Start of the range
Implementation: zope.schema.IntRead Only: False Required: False Default Value: None Allowed Type: int,long
-
max¶ End of the range (including the value itself)
Implementation: zope.schema.IntRead Only: False Required: False Default Value: None Allowed Type: int,long
-
default¶ Default Value
The field default value may be None or a legal field value
Implementation: zope.schema.IntRead Only: False Required: True Default Value: None Allowed Type: int,long
-
-
interface
zope.schema.interfaces.IFloat[source]¶ Extends:
zope.schema.interfaces.IRealField containing exactly the native class
float.IRealis a more general interface, allowing all of floats, ints, and fractions.See also
-
interface
zope.schema.interfaces.IDecimal[source]¶ Extends:
zope.schema.interfaces.INumberField containing a
decimal.Decimal-
min¶ Start of the range
Implementation: zope.schema.DecimalRead Only: False Required: False Default Value: None Allowed Type: decimal.Decimal
-
max¶ End of the range (including the value itself)
Implementation: zope.schema.DecimalRead Only: False Required: False Default Value: None Allowed Type: decimal.Decimal
-
default¶ Default Value
The field default value may be None or a legal field value
Implementation: zope.schema.DecimalRead Only: False Required: True Default Value: None Allowed Type: decimal.Decimal
-
Date/Time¶
-
interface
zope.schema.interfaces.IDatetime[source]¶ Extends:
zope.schema.interfaces.IMinMax,zope.schema.interfaces.IFieldField containing a datetime.
-
interface
zope.schema.interfaces.IDate[source]¶ Extends:
zope.schema.interfaces.IMinMax,zope.schema.interfaces.IFieldField containing a date.
-
interface
zope.schema.interfaces.ITimedelta[source]¶ Extends:
zope.schema.interfaces.IMinMax,zope.schema.interfaces.IFieldField containing a timedelta.
-
interface
zope.schema.interfaces.ITime[source]¶ Extends:
zope.schema.interfaces.IMinMax,zope.schema.interfaces.IFieldField containing a time.
Collections¶
-
interface
zope.schema.interfaces.IIterable[source]¶ Extends:
zope.schema.interfaces.IFieldFields with a value that can be iterated over.
The value needs to support iteration; the implementation mechanism is not constrained. (Either
__iter__()or__getitem__()may be used.)
-
interface
zope.schema.interfaces.IContainer[source]¶ Extends:
zope.schema.interfaces.IFieldFields whose value allows an
x in valuecheck.The value needs to support the
inoperator, but is not constrained in how it does so (whether it defines__contains__()or__getitem__()is immaterial).
-
interface
zope.schema.interfaces.ICollection[source]¶ Extends:
zope.schema.interfaces.IMinMaxLen,zope.schema.interfaces.IIterable,zope.schema.interfaces.IContainerAbstract interface containing a collection value.
The Value must be iterable and may have a min_length/max_length.
-
value_type¶ Value Type
Field value items must conform to the given type, expressed via a Field.
Implementation: zope.schema.ObjectRead Only: False Required: True Default Value: None Must Provide: zope.schema.interfaces.IField
-
unique¶ Unique Members
Specifies whether the members of the collection must be unique.
Implementation: zope.schema.BoolRead Only: False Required: True Default Value: False Allowed Type: bool
-
-
interface
zope.schema.interfaces.ISequence[source]¶ Extends:
zope.schema.interfaces.ICollectionAbstract interface specifying that the value is ordered
-
interface
zope.schema.interfaces.IMutableSequence[source]¶ Extends:
zope.schema.interfaces.ISequenceAbstract interface specifying that the value is ordered and mutable.
New in version 4.6.0.
-
interface
zope.schema.interfaces.IUnorderedCollection[source]¶ Extends:
zope.schema.interfaces.ICollectionAbstract interface specifying that the value cannot be ordered
-
interface
zope.schema.interfaces.IAbstractSet[source]¶ Extends:
zope.schema.interfaces.IUnorderedCollectionAn unordered collection of unique values.
-
unique¶ This ICollection interface attribute must be True
Implementation: zope.schema.BoolRead Only: False Required: True Default Value: None Allowed Type: bool
-
-
interface
zope.schema.interfaces.IAbstractBag[source]¶ Extends:
zope.schema.interfaces.IUnorderedCollectionAn unordered collection of values, with no limitations on whether members are unique
-
unique¶ This ICollection interface attribute must be False
Implementation: zope.schema.BoolRead Only: False Required: True Default Value: None Allowed Type: bool
-
-
interface
zope.schema.interfaces.ITuple[source]¶ Extends:
zope.schema.interfaces.ISequenceField containing a value that implements the API of a conventional Python tuple.
-
interface
zope.schema.interfaces.IList[source]¶ Extends:
zope.schema.interfaces.IMutableSequenceField containing a value that implements the API of a conventional Python list.
-
interface
zope.schema.interfaces.ISet[source]¶ Extends:
zope.schema.interfaces.IAbstractSetField containing a value that implements the API of a Python2.4+ set.
-
interface
zope.schema.interfaces.IFrozenSet[source]¶ Extends:
zope.schema.interfaces.IAbstractSetField containing a value that implements the API of a conventional Python 2.4+ frozenset.
Mappings¶
-
interface
zope.schema.interfaces.IMapping[source]¶ Extends:
zope.schema.interfaces.IMinMaxLen,zope.schema.interfaces.IIterable,zope.schema.interfaces.IContainerField containing an instance of
collections.Mapping.The key_type and value_type fields allow specification of restrictions for keys and values contained in the dict.
-
key_type¶ Field keys must conform to the given type, expressed via a Field.
Implementation: zope.schema.ObjectRead Only: False Required: True Default Value: None Must Provide: zope.schema.interfaces.IField
-
value_type¶ Field values must conform to the given type, expressed via a Field.
Implementation: zope.schema.ObjectRead Only: False Required: True Default Value: None Must Provide: zope.schema.interfaces.IField
-
-
interface
zope.schema.interfaces.IMutableMapping[source]¶ Extends:
zope.schema.interfaces.IMappingField containing an instance of
collections.MutableMapping.
-
interface
zope.schema.interfaces.IDict[source]¶ Extends:
zope.schema.interfaces.IMutableMappingField containing a conventional dict.
Events¶
-
interface
zope.schema.interfaces.IBeforeObjectAssignedEvent[source]¶ An object is going to be assigned to an attribute on another object.
Subscribers to this event can change the object on this event to change what object is going to be assigned. This is useful, e.g. for wrapping or replacing objects before they get assigned to conform to application policy.
-
object¶ The object that is going to be assigned.
-
name¶ The name of the attribute under which the object will be assigned.
-
context¶ The context object where the object will be assigned to.
-
-
interface
zope.schema.interfaces.IFieldEvent[source]¶ -
field¶ The field that has been changed
Implementation: zope.schema.ObjectRead Only: False Required: True Default Value: None Must Provide: zope.schema.interfaces.IField
-
object¶ The object containing the field
-
-
interface
zope.schema.interfaces.IFieldUpdatedEvent[source]¶ Extends:
zope.schema.interfaces.IFieldEventA field has been modified
Subscribers will get the old and the new value together with the field
-
old_value¶ The value of the field before modification
-
new_value¶ The value of the field after modification
-
Vocabularies¶
-
interface
zope.schema.interfaces.ITerm[source]¶ Object representing a single value in a vocabulary.
-
value¶ The value used to represent vocabulary term in a field.
-
-
interface
zope.schema.interfaces.ITokenizedTerm[source]¶ Extends:
zope.schema.interfaces.ITermObject representing a single value in a tokenized vocabulary.
-
token¶ Token which can be used to represent the value on a stream.
The value of this attribute must be a non-empty 7-bit native string (i.e., the
strtype on both Python 2 and 3). Control characters, including newline, are not allowed.
-
-
interface
zope.schema.interfaces.ITitledTokenizedTerm[source]¶ Extends:
zope.schema.interfaces.ITokenizedTermA tokenized term that includes a title.
-
title¶ Title
Implementation: zope.schema.TextLineRead Only: False Required: True Default Value: None Allowed Type: unicode
-
-
interface
zope.schema.interfaces.ISource[source]¶ A set of values from which to choose
Sources represent sets of values. They are used to specify the source for choice fields.
Sources can be large (even infinite), in which case, they need to be queried to find out what their values are.
-
__contains__(value)¶ Return whether the value is available in this source
-
-
interface
zope.schema.interfaces.ISourceQueriables[source]¶ A collection of objects for querying sources
-
getQueriables()¶ Return an iterable of objects that can be queried
The returned obects should be two-tuples with:
A unicode id
The id must uniquely identify the queriable object within the set of queriable objects. Furthermore, in subsequent calls, the same id should be used for a given queriable object.
A queriable object
This is an object for which there is a view provided for searching for items.
-
-
interface
zope.schema.interfaces.IContextSourceBinder[source]¶ -
__call__(context)¶ Return a context-bound instance that implements ISource.
-
-
interface
zope.schema.interfaces.IBaseVocabulary[source]¶ Extends:
zope.schema.interfaces.ISourceRepresentation of a vocabulary.
At this most basic level, a vocabulary only need to support a test for containment. This can be implemented either by __contains__() or by sequence __getitem__() (the later only being useful for vocabularies which are intrinsically ordered).
-
getTerm(value)¶ Return the ITerm object for the term ‘value’.
If ‘value’ is not a valid term, this method raises LookupError.
-
-
interface
zope.schema.interfaces.IIterableVocabulary[source]¶ Vocabulary which supports iteration over allowed values.
The objects iteration provides must conform to the ITerm interface.
-
__iter__()¶ Return an iterator which provides the terms from the vocabulary.
-
__len__()¶ Return the number of valid terms, or sys.maxint.
-
-
interface
zope.schema.interfaces.IIterableSource[source]¶ Extends:
zope.schema.interfaces.ISourceSource which supports iteration over allowed values.
The objects iteration provides must be values from the source.
-
__iter__()¶ Return an iterator which provides the values from the source.
-
__len__()¶ Return the number of valid values, or sys.maxint.
-
-
interface
zope.schema.interfaces.IVocabulary[source]¶ Extends:
zope.schema.interfaces.IIterableVocabulary,zope.schema.interfaces.IBaseVocabularyVocabulary which is iterable.
-
interface
zope.schema.interfaces.IVocabularyTokenized[source]¶ Extends:
zope.schema.interfaces.IVocabularyVocabulary that provides support for tokenized representation.
Terms returned from getTerm() and provided by iteration must conform to ITokenizedTerm.
-
getTermByToken(token)¶ Return an ITokenizedTerm for the passed-in token.
If
tokenis not represented in the vocabulary,LookupErroris raised.
-
-
interface
zope.schema.interfaces.ITreeVocabulary[source]¶ Extends:
zope.schema.interfaces.IVocabularyTokenized,zope.interface.common.mapping.IEnumerableMappingA tokenized vocabulary with a tree-like structure.
The tree is implemented as dictionary, with keys being ITokenizedTerm terms and the values being similar dictionaries. Leaf values are empty dictionaries.
-
interface
zope.schema.interfaces.IVocabularyRegistry[source]¶ Registry that provides
IBaseVocabularyobjects for specific fields.The fields of this package use the vocabulary registry that is returned from
getVocabularyRegistry(). This is a hook function; by default it returns an instance ofVocabularyRegistry, but the functionsetVocabularyRegistry()can be used to change this.In particular, the package zope.vocabularyregistry can be used to install a vocabulary registry that uses the
zope.componentarchitecture.-
get(context, name)¶ Return the vocabulary named name for the content object context.
When the vocabulary cannot be found,
LookupErroris raised.
-
-
interface
zope.schema.interfaces.IVocabularyFactory[source]¶ An object that can create
IBaseVocabulary.Objects that implement this interface can be registered with the default
VocabularyRegistryprovided by this package.Alternatively, zope.vocabularyregistry can be used to install a
IVocabularyRegistrythat looks for named utilities usingzope.component.getUtility()which provide this interface.-
__call__(context)¶ The context provides a location that vocabulary can make use of.
-
Exceptions¶
-
exception
zope.schema._bootstrapinterfaces.ValidationError[source]¶ Bases:
zope.interface.exceptions.InvalidRaised if the Validation process fails.
-
field= None¶ The field that raised the error, if known.
-
value= None¶ The value that failed validation.
-
-
exception
zope.schema.ValidationError¶ The preferred alias for
zope.schema._bootstrapinterfaces.ValidationError.
-
exception
zope.schema.interfaces.StopValidation[source]¶ Bases:
exceptions.ExceptionRaised if the validation is completed early.
Note that this exception should be always caught, since it is just a way for the validator to save time.
-
exception
zope.schema.interfaces.RequiredMissing[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorRequired input is missing.
-
exception
zope.schema.interfaces.WrongType(value, expected_type, name)[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorObject is of wrong type.
Changed in version 4.7.0: Added named arguments to the constructor and the
expected_typefield.-
expected_type= None¶ The type or tuple of types that was expected.
New in version 4.7.0.
-
-
exception
zope.schema.interfaces.ConstraintNotSatisfied[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorConstraint not satisfied
-
exception
zope.schema.interfaces.NotAContainer[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorNot a container
-
exception
zope.schema.interfaces.NotAnIterator[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorNot an iterator
-
exception
zope.schema.interfaces.NotAnInterface(value, name)[source]¶ Bases:
zope.schema._bootstrapinterfaces.WrongType,zope.schema._bootstrapinterfaces.SchemaNotProvidedObject is not an interface.
This is a
WrongTypeexception for backwards compatibility with existingexceptclauses, but it is raised whenIInterface.providedByis not true, so it’s also aSchemaNotProvided. Theexpected_typefield is filled in asIInterface; this is not actually atype, andisinstance(thing, IInterface)is always false.New in version 4.7.0.
-
expected_type= <InterfaceClass zope.interface.interfaces.IInterface>¶
-
Bounds¶
-
exception
zope.schema.interfaces.OutOfBounds(value, bound)[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorA value was out of the allowed bounds.
This is the common superclass for
OrderableOutOfBoundsandLenOutOfBounds, which in turn are the superclasses forTooBigandTooSmall, andTooLongandTooShort, respectively.New in version 4.7.0.
-
TOO_LARGE= <zope.schema._bootstrapinterfaces.TOO_LARGE object>¶ A constant for
violation_direction.
-
TOO_SMALL= <zope.schema._bootstrapinterfaces.TOO_SMALL object>¶ A constant for
violation_direction.
-
violation_direction= None¶ Whether the value was too large or not large enough. One of the values defined by the constants
TOO_LARGEorTOO_SMALL
-
bound= None¶ The value that was exceeded
-
-
exception
zope.schema.interfaces.OrderableOutOfBounds(value, bound)[source]¶ Bases:
zope.schema._bootstrapinterfaces.OutOfBoundsA value was too big or too small in comparison to another value.
New in version 4.7.0.
-
exception
zope.schema.interfaces.LenOutOfBounds(value, bound)[source]¶ Bases:
zope.schema._bootstrapinterfaces.OutOfBoundsThe length of the value was out of bounds.
New in version 4.7.0.
-
exception
zope.schema.interfaces.TooSmall(value, bound)[source]¶ Bases:
zope.schema._bootstrapinterfaces.OrderableOutOfBoundsValue is too small
-
exception
zope.schema.interfaces.TooBig(value, bound)[source]¶ Bases:
zope.schema._bootstrapinterfaces.OrderableOutOfBoundsValue is too big
-
exception
zope.schema.interfaces.TooLong(value, bound)[source]¶ Bases:
zope.schema._bootstrapinterfaces.LenOutOfBoundsValue is too long
-
exception
zope.schema.interfaces.TooShort(value, bound)[source]¶ Bases:
zope.schema._bootstrapinterfaces.LenOutOfBoundsValue is too short
-
exception
zope.schema.interfaces.InvalidValue[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorInvalid value
-
exception
zope.schema.interfaces.WrongContainedType(errors, name)[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorWrong contained type
Changed in version 4.7.0: Added named arguments to the constructor, and the
errorsproperty.-
errors= ()¶ A collection of exceptions raised when validating the value.
New in version 4.7.0.
-
-
exception
zope.schema.interfaces.NotUnique[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorOne or more entries of sequence are not unique.
-
exception
zope.schema.interfaces.SchemaNotFullyImplemented[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorSchema not fully implemented
-
exception
zope.schema.interfaces.SchemaNotProvided(schema, value)[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorSchema not provided
Changed in version 4.7.0: Added named arguments to the constructor and the
schemaproperty.-
schema= None¶ The interface that the value was supposed to provide, but does not.
-
-
exception
zope.schema.interfaces.InvalidURI[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorThe specified URI is not valid.
-
exception
zope.schema.interfaces.InvalidId[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorThe specified id is not valid.
-
exception
zope.schema.interfaces.InvalidDottedName[source]¶ Bases:
zope.schema._bootstrapinterfaces.ValidationErrorThe specified dotted name is not valid.
Schema APIs¶
-
zope.schema.getFieldsInOrder(schema, _field_key=<function <lambda>>)[source]¶ Return a list of (name, value) tuples in native schema order.
-
zope.schema.getFieldNamesInOrder(schema)[source]¶ Return a list of all the Field names in a schema in schema order.
-
zope.schema.getValidationErrors(schema, value)[source] Validate that value conforms to the schema interface schema.
This includes checking for any schema validation errors (using
getSchemaValidationErrors). If that succeeds, then we proceed to check for any declared invariants.Note that this does not include a check to see if the value actually provides the given schema.
Returns: A sequence of (name, zope.interface.Invalid) tuples, where name is None if the error was from an invariant. If the sequence is empty, there were no errors.
-
zope.schema.getSchemaValidationErrors(schema, value)[source] Validate that value conforms to the schema interface schema.
All
zope.schema.interfaces.IFieldmembers of the schema are validated after being bound to value. (Note that we do not check for arbitraryzope.interface.Attributemembers being present.)Returns: A sequence of (name, ValidationError) tuples. A non-empty sequence indicates validation failed.
Field Implementations¶
-
class
zope.schema.Field(title=u'', description=u'', __name__='', required=True, readonly=False, constraint=None, default=None, defaultFactory=None, missing_value=<Not Given>)[source]¶ Bases:
zope.interface.interface.AttributePass in field values as keyword parameters.
Generally, you want to pass either a title and description, or a doc string. If you pass no doc string, it will be computed from the title and description. If you pass a doc string that follows the Python coding style (title line separated from the body by a blank line), the title and description will be computed from the doc string. Unfortunately, the doc string must be passed as a positional argument.
Here are some examples:
>>> from zope.schema._bootstrapfields import Field >>> f = Field() >>> f.__doc__, str(f.title), str(f.description) ('', '', '')
>>> f = Field(title=u'sample') >>> str(f.__doc__), str(f.title), str(f.description) ('sample', 'sample', '')
>>> f = Field(title=u'sample', description=u'blah blah\nblah') >>> str(f.__doc__), str(f.title), str(f.description) ('sample\n\nblah blah\nblah', 'sample', 'blah blah\nblah')
-
getExtraDocLines()[source]¶ Return a list of ReST formatted lines that will be added to the docstring returned by
getDoc().By default, this will include information about the various properties of this object, such as required and readonly status, required type, and so on.
This implementation uses a field list for this.
Subclasses may override or extend.
New in version 4.6.0.
-
-
class
zope.schema.Collection(value_type=<Not Given>, unique=<Not Given>, **kw)[source]¶ Bases:
zope.schema._bootstrapfields.MinMaxLen,zope.schema._bootstrapfields.IterableA generic collection implementing
zope.schema.interfaces.ICollection.Subclasses can define the attribute
value_typeto be a field such as anObjectthat will be checked for each member of the collection. This can then be omitted from the constructor call.They can also define the attribute
_typeto be a concrete class (or tuple of classes) that the collection itself will be checked to be an instance of. This cannot be set in the constructor.Changed in version 4.6.0: Add the ability for subclasses to specify
value_typeandunique, and allow eliding them from the constructor.
-
zope.schema._field.AbstractCollection¶ An alternate name for
Collection.Deprecated since version 4.6.0: Use
Collectioninstead.alias of
zope.schema._field.Collection
-
class
zope.schema.Bool(title=u'', description=u'', __name__='', required=True, readonly=False, constraint=None, default=None, defaultFactory=None, missing_value=<Not Given>)[source]¶ A field representing a Bool.
Changed in version 4.8.0: Implement
zope.schema.interfaces.IFromBytesPass in field values as keyword parameters.
Generally, you want to pass either a title and description, or a doc string. If you pass no doc string, it will be computed from the title and description. If you pass a doc string that follows the Python coding style (title line separated from the body by a blank line), the title and description will be computed from the doc string. Unfortunately, the doc string must be passed as a positional argument.
Here are some examples:
>>> from zope.schema._bootstrapfields import Field >>> f = Field() >>> f.__doc__, str(f.title), str(f.description) ('', '', '')
>>> f = Field(title=u'sample') >>> str(f.__doc__), str(f.title), str(f.description) ('sample', 'sample', '')
>>> f = Field(title=u'sample', description=u'blah blah\nblah') >>> str(f.__doc__), str(f.title), str(f.description) ('sample\n\nblah blah\nblah', 'sample', 'blah blah\nblah')
-
fromUnicode(value)[source]¶ >>> from zope.schema._bootstrapfields import Bool >>> from zope.schema.interfaces import IFromUnicode >>> b = Bool() >>> IFromUnicode.providedBy(b) True >>> b.fromUnicode('True') True >>> b.fromUnicode('') False >>> b.fromUnicode('true') True >>> b.fromUnicode('false') or b.fromUnicode('False') False >>> b.fromUnicode(u'\u2603') False
-
fromBytes(value)[source]¶ >>> from zope.schema._bootstrapfields import Bool >>> from zope.schema.interfaces import IFromBytes >>> b = Bool() >>> IFromBytes.providedBy(b) True >>> b.fromBytes(b'True') True >>> b.fromBytes(b'') False >>> b.fromBytes(b'true') True >>> b.fromBytes(b'false') or b.fromBytes(b'False') False >>> b.fromBytes(u'\u2603'.encode('utf-8')) False
-
-
class
zope.schema.Choice(values=None, vocabulary=None, source=None, **kw)[source]¶ Choice fields can have a value found in a constant or dynamic set of values given by the field definition.
Initialize object.
-
class
zope.schema.Container(title=u'', description=u'', __name__='', required=True, readonly=False, constraint=None, default=None, defaultFactory=None, missing_value=<Not Given>)[source]¶ Pass in field values as keyword parameters.
Generally, you want to pass either a title and description, or a doc string. If you pass no doc string, it will be computed from the title and description. If you pass a doc string that follows the Python coding style (title line separated from the body by a blank line), the title and description will be computed from the doc string. Unfortunately, the doc string must be passed as a positional argument.
Here are some examples:
>>> from zope.schema._bootstrapfields import Field >>> f = Field() >>> f.__doc__, str(f.title), str(f.description) ('', '', '')
>>> f = Field(title=u'sample') >>> str(f.__doc__), str(f.title), str(f.description) ('sample', 'sample', '')
>>> f = Field(title=u'sample', description=u'blah blah\nblah') >>> str(f.__doc__), str(f.title), str(f.description) ('sample\n\nblah blah\nblah', 'sample', 'blah blah\nblah')
-
class
zope.schema.Dict(key_type=None, value_type=None, **kw)[source]¶ Bases:
zope.schema._field.MutableMappingA field representing a Dict.
-
class
zope.schema.Id(min_length=0, max_length=None, **kw)[source]¶ Id field
Values of id fields must be either uris or dotted names.
Changed in version 4.8.0: Implement
zope.schema.interfaces.IFromBytes
-
class
zope.schema.InterfaceField(title=u'', description=u'', __name__='', required=True, readonly=False, constraint=None, default=None, defaultFactory=None, missing_value=<Not Given>)[source]¶ Fields with a value that is an interface (implementing zope.interface.Interface).
Pass in field values as keyword parameters.
Generally, you want to pass either a title and description, or a doc string. If you pass no doc string, it will be computed from the title and description. If you pass a doc string that follows the Python coding style (title line separated from the body by a blank line), the title and description will be computed from the doc string. Unfortunately, the doc string must be passed as a positional argument.
Here are some examples:
>>> from zope.schema._bootstrapfields import Field >>> f = Field() >>> f.__doc__, str(f.title), str(f.description) ('', '', '')
>>> f = Field(title=u'sample') >>> str(f.__doc__), str(f.title), str(f.description) ('sample', 'sample', '')
>>> f = Field(title=u'sample', description=u'blah blah\nblah') >>> str(f.__doc__), str(f.title), str(f.description) ('sample\n\nblah blah\nblah', 'sample', 'blah blah\nblah')
-
class
zope.schema.Iterable(title=u'', description=u'', __name__='', required=True, readonly=False, constraint=None, default=None, defaultFactory=None, missing_value=<Not Given>)[source]¶ Pass in field values as keyword parameters.
Generally, you want to pass either a title and description, or a doc string. If you pass no doc string, it will be computed from the title and description. If you pass a doc string that follows the Python coding style (title line separated from the body by a blank line), the title and description will be computed from the doc string. Unfortunately, the doc string must be passed as a positional argument.
Here are some examples:
>>> from zope.schema._bootstrapfields import Field >>> f = Field() >>> f.__doc__, str(f.title), str(f.description) ('', '', '')
>>> f = Field(title=u'sample') >>> str(f.__doc__), str(f.title), str(f.description) ('sample', 'sample', '')
>>> f = Field(title=u'sample', description=u'blah blah\nblah') >>> str(f.__doc__), str(f.title), str(f.description) ('sample\n\nblah blah\nblah', 'sample', 'blah blah\nblah')
-
class
zope.schema.List(value_type=<Not Given>, unique=<Not Given>, **kw)[source]¶ Bases:
zope.schema._field.MutableSequenceA field representing a List.
-
class
zope.schema.Mapping(key_type=None, value_type=None, **kw)[source]¶ A field representing a mapping.
New in version 4.6.0.
-
class
zope.schema.MutableMapping(key_type=None, value_type=None, **kw)[source]¶ Bases:
zope.schema._field.MappingA field representing a mutable mapping.
New in version 4.6.0.
-
class
zope.schema.MutableSequence(value_type=<Not Given>, unique=<Not Given>, **kw)[source]¶ Bases:
zope.schema._field.SequenceA field representing a mutable sequence.
New in version 4.6.0.
-
class
zope.schema.MinMaxLen(min_length=0, max_length=None, **kw)[source]¶ Bases:
objectExpresses constraints on the length of a field.
MinMaxLen is a mixin used in combination with Field.
-
class
zope.schema.Object(schema=<Not Given>, *, validate_invariants=True, **kwargs)[source]¶ Implementation of
zope.schema.interfaces.IObject.Create an
IObjectfield. The keyword arguments are as forField.Changed in version 4.6.0: Add the keyword argument validate_invariants. When true (the default), the schema’s
validateInvariantsmethod will be invoked to check the@invariantproperties of the schema.Changed in version 4.6.0: The schema argument can be ommitted in a subclass that specifies a
schemaattribute.-
getExtraDocLines()[source]¶ Return a list of ReST formatted lines that will be added to the docstring returned by
getDoc().By default, this will include information about the various properties of this object, such as required and readonly status, required type, and so on.
This implementation uses a field list for this.
Subclasses may override or extend.
New in version 4.6.0.
-
-
class
zope.schema.Orderable(min=None, max=None, default=None, **kw)[source]¶ Bases:
objectValues of ordered fields can be sorted.
They can be restricted to a range of values.
Orderable is a mixin used in combination with Field.
-
class
zope.schema.Set(*args, **kwargs)[source]¶ Bases:
zope.schema._field._AbstractSetA field representing a set.
-
class
zope.schema.Sequence(value_type=<Not Given>, unique=<Not Given>, **kw)[source]¶ Bases:
zope.schema._field.CollectionA field representing an ordered sequence.
New in version 4.6.0.
-
class
zope.schema.Timedelta(min=None, max=None, default=None, **kw)[source]¶ Field containing a timedelta.
-
class
zope.schema.Tuple(value_type=<Not Given>, unique=<Not Given>, **kw)[source]¶ Bases:
zope.schema._field.SequenceA field representing a Tuple.
-
class
zope.schema.URI(min_length=0, max_length=None, **kw)[source]¶ URI schema field.
URIs can be validated from both unicode values and bytes values, producing a native text string in both cases:
>>> from zope.schema import URI >>> field = URI() >>> field.fromUnicode(u' https://example.com ') 'https://example.com' >>> field.fromBytes(b' https://example.com ') 'https://example.com'
Changed in version 4.8.0: Implement
zope.schema.interfaces.IFromBytes
Strings¶
-
class
zope.schema.ASCII(min_length=0, max_length=None, **kw)[source]¶ Field containing a 7-bit ASCII string. No characters > DEL (chr(127)) are allowed
The value might be constrained to be with length limits.
-
class
zope.schema.ASCIILine(min_length=0, max_length=None, **kw)[source]¶ Field containing a 7-bit ASCII string without newlines.
-
class
zope.schema.Bytes(min_length=0, max_length=None, **kw)[source]¶ Field containing a byte string (like the python str).
The value might be constrained to be with length limits.
-
class
zope.schema.BytesLine(min_length=0, max_length=None, **kw)[source]¶ A
Bytesfield with no newlines.
-
class
zope.schema.Text(*args, **kw)[source]¶ A field containing text used for human discourse.
-
fromUnicode(value)[source]¶ >>> from zope.schema import Text >>> t = Text(constraint=lambda v: 'x' in v) >>> t.fromUnicode(b"foo x spam") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... zope.schema._bootstrapinterfaces.WrongType: ('foo x spam', <type 'unicode'>, '') >>> result = t.fromUnicode(u"foo x spam") >>> isinstance(result, bytes) False >>> str(result) 'foo x spam' >>> t.fromUnicode(u"foo spam") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... zope.schema._bootstrapinterfaces.ConstraintNotSatisfied: (u'foo spam', '')
-
-
class
zope.schema.NativeString(min_length=0, max_length=None, **kw)[source]¶ A native string is always the type
str.In addition to
INativeString, this implementsIFromUnicodeandIFromBytes.
-
class
zope.schema.NativeStringLine(min_length=0, max_length=None, **kw)[source]¶ A native string is always the type
str; this field excludes newlines.In addition to
INativeStringLine, this implementsIFromUnicodeandIFromBytes.
-
class
zope.schema.DottedName(*args, **kw)[source]¶ Dotted name field.
Values of DottedName fields must be Python-style dotted names.
Dotted names can be validated from both unicode values and bytes values, producing a native text string in both cases:
>>> from zope.schema import DottedName >>> field = DottedName() >>> field.fromUnicode(u'zope.schema') 'zope.schema' >>> field.fromBytes(b'zope.schema') 'zope.schema' >>> field.fromUnicode(u'zope._schema') 'zope._schema'
Changed in version 4.8.0: Implement
zope.schema.interfaces.IFromBytesChanged in version 4.9.0: Allow leading underscores in each component.
-
class
zope.schema.PythonIdentifier(min_length=0, max_length=None, **kw)[source]¶ This field describes a python identifier, i.e. a variable name.
Empty strings are allowed.
Identifiers can be validated from both unicode values and bytes values, producing a native text string in both cases:
>>> from zope.schema import PythonIdentifier >>> field = PythonIdentifier() >>> field.fromUnicode(u'zope') 'zope' >>> field.fromBytes(b'_zope') '_zope' >>> field.fromUnicode(u' ') ''
New in version 4.9.0.
Numbers¶
-
class
zope.schema.Number(min=None, max=None, default=None, **kw)[source]¶ Bases:
zope.schema._bootstrapfields.Orderable,zope.schema._bootstrapfields.FieldA field representing a
numbers.Numberand implementingzope.schema.interfaces.INumber.The
fromUnicode()method will attempt to use the smallest or strictest possible type to represent incoming strings:>>> from zope.schema._bootstrapfields import Number >>> f = Number() >>> f.fromUnicode(u"1") 1 >>> f.fromUnicode(u"125.6") 125.6 >>> f.fromUnicode(u"1+0j") (1+0j) >>> f.fromUnicode(u"1/2") Fraction(1, 2) >>> f.fromUnicode(str(2**11234) + '.' + str(2**256)) ... Decimal('590...936') >>> f.fromUnicode(u"not a number") Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number'
Similarly,
fromBytes()will do the same for incoming byte strings:>>> from zope.schema._bootstrapfields import Number >>> f = Number() >>> f.fromBytes(b"1") 1 >>> f.fromBytes(b"125.6") 125.6 >>> f.fromBytes(b"1+0j") (1+0j) >>> f.fromBytes(b"1/2") Fraction(1, 2) >>> f.fromBytes((str(2**11234) + '.' + str(2**256)).encode('ascii')) ... Decimal('590...936') >>> f.fromBytes(b"not a number") Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number'
New in version 4.6.0.
Changed in version 4.8.0: Implement
zope.schema.interfaces.IFromBytes
-
class
zope.schema.Complex(min=None, max=None, default=None, **kw)[source]¶ Bases:
zope.schema._bootstrapfields.NumberA field representing a
numbers.Complexand implementingzope.schema.interfaces.IComplex.The
fromUnicode()method is like that forNumber, but doesn’t allow Decimals:>>> from zope.schema._bootstrapfields import Complex >>> f = Complex() >>> f.fromUnicode(u"1") 1 >>> f.fromUnicode(u"125.6") 125.6 >>> f.fromUnicode(u"1+0j") (1+0j) >>> f.fromUnicode(u"1/2") Fraction(1, 2) >>> f.fromUnicode(str(2**11234) + '.' + str(2**256)) ... inf >>> f.fromUnicode(u"not a number") Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number'
Similarly for
fromBytes():>>> from zope.schema._bootstrapfields import Complex >>> f = Complex() >>> f.fromBytes(b"1") 1 >>> f.fromBytes(b"125.6") 125.6 >>> f.fromBytes(b"1+0j") (1+0j) >>> f.fromBytes(b"1/2") Fraction(1, 2) >>> f.fromBytes((str(2**11234) + '.' + str(2**256)).encode('ascii')) ... # doctest: +ELLIPSIS inf >>> f.fromBytes(b"not a number") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number'
New in version 4.6.0.
-
class
zope.schema.Real(min=None, max=None, default=None, **kw)[source]¶ Bases:
zope.schema._bootstrapfields.ComplexA field representing a
numbers.Realand implementingzope.schema.interfaces.IReal.The
fromUnicode()method is like that forComplex, but doesn’t allow Decimals or complex numbers:>>> from zope.schema._bootstrapfields import Real >>> f = Real() >>> f.fromUnicode("1") 1 >>> f.fromUnicode("125.6") 125.6 >>> f.fromUnicode("1+0j") Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Fraction: '1+0j' >>> f.fromUnicode("1/2") Fraction(1, 2) >>> f.fromUnicode(str(2**11234) + '.' + str(2**256)) ... inf >>> f.fromUnicode("not a number") Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number'
New in version 4.6.0.
-
class
zope.schema.Rational(min=None, max=None, default=None, **kw)[source]¶ Bases:
zope.schema._bootstrapfields.RealA field representing a
numbers.Rationaland implementingzope.schema.interfaces.IRational.The
fromUnicode()method is like that forReal, but does not allow arbitrary floating point numbers:>>> from zope.schema._bootstrapfields import Rational >>> f = Rational() >>> f.fromUnicode("1") 1 >>> f.fromUnicode("1/2") Fraction(1, 2) >>> f.fromUnicode("125.6") Fraction(628, 5) >>> f.fromUnicode("1+0j") Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Fraction: '1+0j' >>> f.fromUnicode(str(2**11234) + '.' + str(2**256)) ... Fraction(195..., 330...) >>> f.fromUnicode("not a number") Traceback (most recent call last): ... InvalidNumberLiteral: Invalid literal for Decimal: 'not a number'
New in version 4.6.0.
-
class
zope.schema.Integral(min=None, max=None, default=None, **kw)[source]¶ Bases:
zope.schema._bootstrapfields.RationalA field representing a
numbers.Integraland implementingzope.schema.interfaces.IIntegral.The
fromUnicode()method only allows integral values:>>> from zope.schema._bootstrapfields import Integral >>> f = Integral() >>> f.fromUnicode("125") 125 >>> f.fromUnicode("125.6") Traceback (most recent call last): ... InvalidIntLiteral: invalid literal for int(): 125.6
Similarly for
fromBytes():>>> from zope.schema._bootstrapfields import Integral >>> f = Integral() >>> f.fromBytes(b"125") 125 >>> f.fromBytes(b"125.6") #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... InvalidIntLiteral: invalid literal for int(): 125.6
New in version 4.6.0.
-
class
zope.schema.Float(min=None, max=None, default=None, **kw)[source]¶ Bases:
zope.schema._bootstrapfields.RealA field representing a native
floatand implementingzope.schema.interfaces.IFloat.The class
zope.schema.Realis a more general version, accepting floats, integers, and fractions.The
fromUnicode()method only accepts values that can be parsed by thefloatconstructor:>>> from zope.schema._field import Float >>> f = Float() >>> f.fromUnicode("1") 1.0 >>> f.fromUnicode("125.6") 125.6 >>> f.fromUnicode("1+0j") Traceback (most recent call last): ... InvalidFloatLiteral: Invalid literal for float(): 1+0j >>> f.fromUnicode("1/2") Traceback (most recent call last): ... InvalidFloatLiteral: invalid literal for float(): 1/2 >>> f.fromUnicode(str(2**11234) + '.' + str(2**256)) ... inf >>> f.fromUnicode("not a number") Traceback (most recent call last): ... InvalidFloatLiteral: could not convert string to float: not a number
Likewise for
fromBytes():>>> from zope.schema._field import Float >>> f = Float() >>> f.fromBytes(b"1") 1.0 >>> f.fromBytes(b"125.6") 125.6 >>> f.fromBytes(b"1+0j") Traceback (most recent call last): ... InvalidFloatLiteral: Invalid literal for float(): 1+0j >>> f.fromBytes(b"1/2") Traceback (most recent call last): ... InvalidFloatLiteral: invalid literal for float(): 1/2 >>> f.fromBytes((str(2**11234) + '.' + str(2**256)).encode('ascii')) ... inf >>> f.fromBytes(b"not a number") Traceback (most recent call last): ... InvalidFloatLiteral: could not convert string to float: not a number
-
class
zope.schema.Int(min=None, max=None, default=None, **kw)[source]¶ Bases:
zope.schema._bootstrapfields.IntegralA field representing a native integer type. and implementing
zope.schema.interfaces.IInt.
-
class
zope.schema.Decimal(min=None, max=None, default=None, **kw)[source]¶ Bases:
zope.schema._bootstrapfields.NumberA field representing a native
decimal.Decimaland implementingzope.schema.interfaces.IDecimal.The
fromUnicode()method only accepts values that can be parsed by theDecimalconstructor:>>> from zope.schema._field import Decimal >>> f = Decimal() >>> f.fromUnicode("1") Decimal('1') >>> f.fromUnicode("125.6") Decimal('125.6') >>> f.fromUnicode("1+0j") Traceback (most recent call last): ... InvalidDecimalLiteral: Invalid literal for Decimal(): 1+0j >>> f.fromUnicode("1/2") Traceback (most recent call last): ... InvalidDecimalLiteral: Invalid literal for Decimal(): 1/2 >>> f.fromUnicode(str(2**11234) + '.' + str(2**256)) ... Decimal('5901...936') >>> f.fromUnicode("not a number") Traceback (most recent call last): ... InvalidDecimalLiteral: could not convert string to float: not a number
Likewise for
fromBytes():>>> from zope.schema._field import Decimal >>> f = Decimal() >>> f.fromBytes(b"1") Decimal('1') >>> f.fromBytes(b"125.6") Decimal('125.6') >>> f.fromBytes(b"1+0j") Traceback (most recent call last): ... InvalidDecimalLiteral: Invalid literal for Decimal(): 1+0j >>> f.fromBytes(b"1/2") Traceback (most recent call last): ... InvalidDecimalLiteral: Invalid literal for Decimal(): 1/2 >>> f.fromBytes((str(2**11234) + '.' + str(2**256)).encode("ascii")) ... Decimal('5901...936') >>> f.fromBytes(b"not a number") Traceback (most recent call last): ... InvalidDecimalLiteral: could not convert string to float: not a number
Vocabularies¶
Vocabulary support for schema.
-
class
zope.schema.vocabulary.SimpleTerm(value, token=None, title=None)[source]¶ Bases:
objectSimple tokenized term used by SimpleVocabulary.
Changed in version 4.6.0: Implement equality and hashing based on the value, token and title.
Create a term for value and token. If token is omitted, str(value) is used for the token, escaping any non-ASCII characters.
If title is provided, term implements
zope.schema.interfaces.ITitledTokenizedTerm.
-
class
zope.schema.vocabulary.SimpleVocabulary(terms, *interfaces, **kwargs)[source]¶ Bases:
objectVocabulary that works from a sequence of terms.
Changed in version 4.6.0: Implement equality and hashing based on the terms list and interfaces implemented by this object.
Initialize the vocabulary given a list of terms.
The vocabulary keeps a reference to the list of terms passed in; it should never be modified while the vocabulary is used.
One or more interfaces may also be provided so that alternate widgets may be bound without subclassing.
By default, ValueErrors are thrown if duplicate values or tokens are passed in. If you want to swallow these exceptions, pass in
swallow_duplicates=True. In this case, the values will override themselves.-
classmethod
fromItems(items, *interfaces)[source]¶ Construct a vocabulary from a list of (token, value) pairs or (token, value, title) triples. The list does not have to be homogeneous.
The order of the items is preserved as the order of the terms in the vocabulary. Terms are created by calling the class method
createTerm`()with the pair or triple.One or more interfaces may also be provided so that alternate widgets may be bound without subclassing.
Changed in version 4.6.0: Allow passing in triples to set item titles.
-
classmethod
fromValues(values, *interfaces)[source]¶ Construct a vocabulary from a simple list.
Values of the list become both the tokens and values of the terms in the vocabulary. The order of the values is preserved as the order of the terms in the vocabulary. Tokens are created by calling the class method
createTerm()with the value as the only parameter.One or more interfaces may also be provided so that alternate widgets may be bound without subclassing.
-
classmethod
-
class
zope.schema.vocabulary.TreeVocabulary(terms, *interfaces)[source]¶ Bases:
objectVocabulary that relies on a tree (i.e nested) structure.
Initialize the vocabulary given a recursive dict (i.e a tree) with ITokenizedTerm objects for keys and self-similar dicts representing the branches for values.
Refer to the method fromDict for more details.
Concerning the ITokenizedTerm keys, the ‘value’ and ‘token’ attributes of each key (including nested ones) must be unique.
One or more interfaces may also be provided so that alternate widgets may be bound without subclassing.
-
terms_factory¶ alias of
collections.OrderedDict
-
get(key, default=None)[source]¶ Get a value for a key
The default is returned if there is no value for the key.
-
classmethod
fromDict(dict_, *interfaces)[source]¶ Constructs a vocabulary from a dictionary-like object (like dict or OrderedDict), that has tuples for keys.
The tuples should have either 2 or 3 values, i.e: (token, value, title) or (token, value). Only tuples that have three values will create a
zope.schema.interfaces.ITitledTokenizedTerm.For example, a dict with 2-valued tuples:
dict_ = { ('exampleregions', 'Regions used in ATVocabExample'): { ('aut', 'Austria'): { ('tyr', 'Tyrol'): { ('auss', 'Ausserfern'): {}, } }, ('ger', 'Germany'): { ('bav', 'Bavaria'):{} }, } }
One or more interfaces may also be provided so that alternate widgets may be bound without subclassing.
Changed in version 4.6.0: Only create
ITitledTokenizedTermwhen a title is actually provided.
-
-
exception
zope.schema.vocabulary.VocabularyRegistryError(name)[source]¶ Bases:
exceptions.LookupErrorA specialized subclass of
LookupErrorraised for unknown (unregistered) vocabularies.See also
-
class
zope.schema.vocabulary.VocabularyRegistry[source]¶ Bases:
objectDefault implementation of
zope.schema.interfaces.IVocabularyRegistry.An instance of this class is used by default by
getVocabularyRegistry(), which in turn is used byChoicefields.Named vocabularies must be manually registered with this object using
register(). This associates a vocabulary name with azope.schema.interfaces.IVocabularyFactory.An alternative to this is to use the
zope.componentregistry via zope.vocabularyregistry.
Accessors¶
Field accessors¶
Accessors are used to model methods used to access data defined by fields. Accessors are fields that work by decorating existing fields.
To define accessors in an interface, use the accessors function:
class IMyInterface(Interface):
getFoo, setFoo = accessors(Text(title=u'Foo', ...))
getBar = accessors(TextLine(title=u'Foo', readonly=True, ...)
Normally a read accessor and a write accessor are defined. Only a read accessor is defined for read-only fields.
Read accessors function as access method specifications and as field specifications. Write accessors are solely method specifications.