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.IValidatable

Basic 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.TextLine
Read Only:False
Required:False
Default Value:u’‘
Allowed Type:unicode
description

Description

A description of the field

Implementation:zope.schema.Text
Read Only:False
Required:False
Default Value:u’‘
Allowed Type:unicode
required

Required

Tells whether a field requires its value to exist.

Implementation:zope.schema.Bool
Read 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.Bool
Read 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.Field
Read 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.Field
Read 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.Int
Read 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.IField

Field 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.Field
Read Only:False
Required:False
Default Value:None
vocabularyName

Vocabulary name

Vocabulary name to lookup in the vocabulary registry

Implementation:zope.schema.TextLine
Read 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.IField

Field 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.IField

A 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.IOrderable

Field 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.Field
Read Only:False
Required:False
Default Value:None
max

End of the range (including the value itself)

Implementation:zope.schema.Field
Read Only:False
Required:False
Default Value:None
interface zope.schema.interfaces.IMinMaxLen[source]

Extends: zope.schema.interfaces.ILen

Field requiring the length of its value to be within a range

min_length

Minimum length

Value after whitespace processing cannot have less than min_length characters (if a string type) or elements (if another sequence type). If min_length is None, there is no minimum.

Implementation:zope.schema.Int
Read 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_length characters (if a string type) or elements (if another sequence type). If max_length is None, there is no maximum.

Implementation:zope.schema.Int
Read Only:False
Required:False
Default Value:None
Allowed Type:int, long
interface zope.schema.interfaces.IInterfaceField[source]

Extends: zope.schema.interfaces.IField

Fields with a value that is an interface (implementing zope.interface.Interface).

interface zope.schema.interfaces.IBool[source]

Extends: zope.schema.interfaces.IField

Boolean Field.

default

Default Value

The field default value may be None or a legal field value

Implementation:zope.schema.Bool
Read Only:False
Required:True
Default Value:None
Allowed Type:bool
interface zope.schema.interfaces.IObject[source]

Extends: zope.schema.interfaces.IField

Field 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.Object
Read Only:False
Required:True
Default Value:None
Must Provide:zope.interface.interfaces.IInterface
validate_invariants

Validate Invariants

A boolean that says whether schema.validateInvariants is called from self.validate(). The default is true.

Implementation:zope.schema.Bool
Read Only:False
Required:True
Default Value:True
Allowed Type:bool

Conversions

interface zope.schema.interfaces.IFromBytes[source]

Parse a byte string to a value.

If the string needs to be decoded, decoding is done using UTF-8.

New in version 4.8.0.

fromBytes(value)

Convert a byte string to a value.

interface zope.schema.interfaces.IFromUnicode[source]

Parse a unicode string to a value

We will often adapt fields to this interface to support views and other applications that need to convert raw data as unicode values.

fromUnicode(value)

Convert a unicode string to a value.

Strings

interface zope.schema.interfaces.IBytes[source]

Extends: zope.schema.interfaces.IMinMaxLen, zope.schema.interfaces.IIterable, zope.schema.interfaces.IField

Field 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.IBytes

Field containing a byte string without newlines.

interface zope.schema.interfaces.IText[source]

Extends: zope.schema.interfaces.IMinMaxLen, zope.schema.interfaces.IIterable, zope.schema.interfaces.IField

Field containing a unicode string.

interface zope.schema.interfaces.ITextLine[source]

Extends: zope.schema.interfaces.IText

Field containing a unicode string without newlines.

interface zope.schema.interfaces.IASCII[source]

Extends: zope.schema.interfaces.INativeString

Field 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.IASCII

Field containing a 7-bit ASCII string without newlines.

interface zope.schema.interfaces.INativeString[source]

Extends: zope.schema.interfaces.IBytes

A field that always contains the native str type.

Changed in version 4.9.0: This is now a distinct type instead of an alias for either IText or IBytes, depending on the platform.

interface zope.schema.interfaces.INativeStringLine[source]

Extends: zope.schema.interfaces.IBytesLine

A field that always contains the native str type, without any newlines.

Changed in version 4.9.0: This is now a distinct type instead of an alias for either ITextLine or IBytesLine, depending on the platform.

interface zope.schema.interfaces.IPassword[source]

Extends: zope.schema.interfaces.ITextLine

Field containing a unicode string without newlines that is a password.

interface zope.schema.interfaces.IURI[source]

Extends: zope.schema.interfaces.INativeStringLine

A field containing an absolute URI

interface zope.schema.interfaces.IId[source]

Extends: zope.schema.interfaces.INativeStringLine

A 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.INativeStringLine

A single Python identifier, such as a variable name.

New in version 4.9.0.

interface zope.schema.interfaces.IDottedName[source]

Extends: zope.schema.interfaces.INativeStringLine

Dotted name field.

Values of DottedName fields must be Python-style dotted names.

min_dots

Minimum number of dots

Implementation:zope.schema.Int
Read 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.Int
Read 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.IField

Field containing a generic number: numbers.Number.

New in version 4.6.0.

min

Start of the range

Implementation:zope.schema.Number
Read Only:False
Required:False
Default Value:None
Allowed Type:numbers.Number
max

End of the range (including the value itself)

Implementation:zope.schema.Number
Read 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.Number
Read Only:False
Required:True
Default Value:None
Allowed Type:numbers.Number
interface zope.schema.interfaces.IComplex[source]

Extends: zope.schema.interfaces.INumber

Field containing a complex number: numbers.Complex.

See also

zope.schema.Real

New in version 4.6.0.

min

Start of the range

Implementation:zope.schema.Complex
Read Only:False
Required:False
Default Value:None
Allowed Type:numbers.Complex
max

End of the range (including the value itself)

Implementation:zope.schema.Complex
Read 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.Complex
Read Only:False
Required:True
Default Value:None
Allowed Type:numbers.Complex
interface zope.schema.interfaces.IReal[source]

Extends: zope.schema.interfaces.IComplex

Field containing a real number: numbers.IReal.

See also

zope.schema.Real

New in version 4.6.0.

min

Start of the range

Implementation:zope.schema.Real
Read Only:False
Required:False
Default Value:None
Allowed Type:numbers.Real
max

End of the range (including the value itself)

Implementation:zope.schema.Real
Read 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.Real
Read Only:False
Required:True
Default Value:None
Allowed Type:numbers.Real
interface zope.schema.interfaces.IRational[source]

Extends: zope.schema.interfaces.IReal

Field containing a rational number: numbers.IRational.

New in version 4.6.0.

min

Start of the range

Implementation:zope.schema.Rational
Read Only:False
Required:False
Default Value:None
Allowed Type:numbers.Rational
max

End of the range (including the value itself)

Implementation:zope.schema.Rational
Read 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.Rational
Read Only:False
Required:True
Default Value:None
Allowed Type:numbers.Rational
interface zope.schema.interfaces.IIntegral[source]

Extends: zope.schema.interfaces.IRational

Field containing an integral number: class:numbers.Integral.

New in version 4.6.0.

min

Start of the range

Implementation:zope.schema.Integral
Read Only:False
Required:False
Default Value:None
Allowed Type:numbers.Integral
max

End of the range (including the value itself)

Implementation:zope.schema.Integral
Read 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.Integral
Read Only:False
Required:True
Default Value:None
Allowed Type:numbers.Integral
interface zope.schema.interfaces.IInt[source]

Extends: zope.schema.interfaces.IIntegral

Field containing exactly the native class int (or, on Python 2, long).

See also

zope.schema.Int

min

Start of the range

Implementation:zope.schema.Int
Read Only:False
Required:False
Default Value:None
Allowed Type:int, long
max

End of the range (including the value itself)

Implementation:zope.schema.Int
Read 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.Int
Read Only:False
Required:True
Default Value:None
Allowed Type:int, long
interface zope.schema.interfaces.IFloat[source]

Extends: zope.schema.interfaces.IReal

Field containing exactly the native class float.

IReal is a more general interface, allowing all of floats, ints, and fractions.

interface zope.schema.interfaces.IDecimal[source]

Extends: zope.schema.interfaces.INumber

Field containing a decimal.Decimal

Date/Time

interface zope.schema.interfaces.IDatetime[source]

Extends: zope.schema.interfaces.IMinMax, zope.schema.interfaces.IField

Field containing a datetime.

interface zope.schema.interfaces.IDate[source]

Extends: zope.schema.interfaces.IMinMax, zope.schema.interfaces.IField

Field containing a date.

interface zope.schema.interfaces.ITimedelta[source]

Extends: zope.schema.interfaces.IMinMax, zope.schema.interfaces.IField

Field containing a timedelta.

interface zope.schema.interfaces.ITime[source]

Extends: zope.schema.interfaces.IMinMax, zope.schema.interfaces.IField

Field containing a time.

Collections

interface zope.schema.interfaces.IIterable[source]

Extends: zope.schema.interfaces.IField

Fields 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.IField

Fields whose value allows an x in value check.

The value needs to support the in operator, 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.IContainer

Abstract 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.Object
Read 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.Bool
Read Only:False
Required:True
Default Value:False
Allowed Type:bool
interface zope.schema.interfaces.ISequence[source]

Extends: zope.schema.interfaces.ICollection

Abstract interface specifying that the value is ordered

interface zope.schema.interfaces.IMutableSequence[source]

Extends: zope.schema.interfaces.ISequence

Abstract 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.ICollection

Abstract interface specifying that the value cannot be ordered

interface zope.schema.interfaces.IAbstractSet[source]

Extends: zope.schema.interfaces.IUnorderedCollection

An unordered collection of unique values.

unique

This ICollection interface attribute must be True

Implementation:zope.schema.Bool
Read Only:False
Required:True
Default Value:None
Allowed Type:bool
interface zope.schema.interfaces.IAbstractBag[source]

Extends: zope.schema.interfaces.IUnorderedCollection

An unordered collection of values, with no limitations on whether members are unique

unique

This ICollection interface attribute must be False

Implementation:zope.schema.Bool
Read Only:False
Required:True
Default Value:None
Allowed Type:bool
interface zope.schema.interfaces.ITuple[source]

Extends: zope.schema.interfaces.ISequence

Field containing a value that implements the API of a conventional Python tuple.

interface zope.schema.interfaces.IList[source]

Extends: zope.schema.interfaces.IMutableSequence

Field containing a value that implements the API of a conventional Python list.

interface zope.schema.interfaces.ISet[source]

Extends: zope.schema.interfaces.IAbstractSet

Field containing a value that implements the API of a Python2.4+ set.

interface zope.schema.interfaces.IFrozenSet[source]

Extends: zope.schema.interfaces.IAbstractSet

Field 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.IContainer

Field 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.Object
Read 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.Object
Read Only:False
Required:True
Default Value:None
Must Provide:zope.schema.interfaces.IField
interface zope.schema.interfaces.IMutableMapping[source]

Extends: zope.schema.interfaces.IMapping

Field containing an instance of collections.MutableMapping.

interface zope.schema.interfaces.IDict[source]

Extends: zope.schema.interfaces.IMutableMapping

Field 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.Object
Read 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.IFieldEvent

A 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.ITerm

Object 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 str type on both Python 2 and 3). Control characters, including newline, are not allowed.

interface zope.schema.interfaces.ITitledTokenizedTerm[source]

Extends: zope.schema.interfaces.ITokenizedTerm

A tokenized term that includes a title.

title

Title

Implementation:zope.schema.TextLine
Read 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.ISource

Representation 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.ISource

Source 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.IBaseVocabulary

Vocabulary which is iterable.

interface zope.schema.interfaces.IVocabularyTokenized[source]

Extends: zope.schema.interfaces.IVocabulary

Vocabulary 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 token is not represented in the vocabulary, LookupError is raised.

interface zope.schema.interfaces.ITreeVocabulary[source]

Extends: zope.schema.interfaces.IVocabularyTokenized, zope.interface.common.mapping.IEnumerableMapping

A 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 IBaseVocabulary objects 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 of VocabularyRegistry, but the function setVocabularyRegistry() can be used to change this.

In particular, the package zope.vocabularyregistry can be used to install a vocabulary registry that uses the zope.component architecture.

get(context, name)

Return the vocabulary named name for the content object context.

When the vocabulary cannot be found, LookupError is raised.

interface zope.schema.interfaces.IVocabularyFactory[source]

An object that can create IBaseVocabulary.

Objects that implement this interface can be registered with the default VocabularyRegistry provided by this package.

Alternatively, zope.vocabularyregistry can be used to install a IVocabularyRegistry that looks for named utilities using zope.component.getUtility() which provide this interface.

__call__(context)

The context provides a location that the vocabulary can make use of.

Exceptions

exception zope.schema._bootstrapinterfaces.ValidationError[source]

Bases: zope.interface.exceptions.Invalid

Raised 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.Exception

Raised 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.ValidationError

Required input is missing.

exception zope.schema.interfaces.WrongType(value, expected_type, name)[source]

Bases: zope.schema._bootstrapinterfaces.ValidationError

Object is of wrong type.

Changed in version 4.7.0: Added named arguments to the constructor and the expected_type field.

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.ValidationError

Constraint not satisfied

exception zope.schema.interfaces.NotAContainer[source]

Bases: zope.schema._bootstrapinterfaces.ValidationError

Not a container

exception zope.schema.interfaces.NotAnIterator[source]

Bases: zope.schema._bootstrapinterfaces.ValidationError

Not an iterator

exception zope.schema.interfaces.NotAnInterface(value, name)[source]

Bases: zope.schema._bootstrapinterfaces.WrongType, zope.schema._bootstrapinterfaces.SchemaNotProvided

Object is not an interface.

This is a WrongType exception for backwards compatibility with existing except clauses, but it is raised when IInterface.providedBy is not true, so it’s also a SchemaNotProvided. The expected_type field is filled in as IInterface; this is not actually a type, and isinstance(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.ValidationError

A value was out of the allowed bounds.

This is the common superclass for OrderableOutOfBounds and LenOutOfBounds, which in turn are the superclasses for TooBig and TooSmall, and TooLong and TooShort, 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_LARGE or TOO_SMALL

bound = None

The value that was exceeded

exception zope.schema.interfaces.OrderableOutOfBounds(value, bound)[source]

Bases: zope.schema._bootstrapinterfaces.OutOfBounds

A 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.OutOfBounds

The 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.OrderableOutOfBounds

Value is too small

exception zope.schema.interfaces.TooBig(value, bound)[source]

Bases: zope.schema._bootstrapinterfaces.OrderableOutOfBounds

Value is too big

exception zope.schema.interfaces.TooLong(value, bound)[source]

Bases: zope.schema._bootstrapinterfaces.LenOutOfBounds

Value is too long

exception zope.schema.interfaces.TooShort(value, bound)[source]

Bases: zope.schema._bootstrapinterfaces.LenOutOfBounds

Value is too short

exception zope.schema.interfaces.InvalidValue[source]

Bases: zope.schema._bootstrapinterfaces.ValidationError

Invalid value

exception zope.schema.interfaces.WrongContainedType(errors, name)[source]

Bases: zope.schema._bootstrapinterfaces.ValidationError

Wrong contained type

Changed in version 4.7.0: Added named arguments to the constructor, and the errors property.

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.ValidationError

One or more entries of sequence are not unique.

exception zope.schema.interfaces.SchemaNotFullyImplemented[source]

Bases: zope.schema._bootstrapinterfaces.ValidationError

Schema not fully implemented

exception zope.schema.interfaces.SchemaNotProvided(schema, value)[source]

Bases: zope.schema._bootstrapinterfaces.ValidationError

Schema not provided

Changed in version 4.7.0: Added named arguments to the constructor and the schema property.

schema = None

The interface that the value was supposed to provide, but does not.

exception zope.schema.interfaces.InvalidURI[source]

Bases: zope.schema._bootstrapinterfaces.ValidationError

The specified URI is not valid.

exception zope.schema.interfaces.InvalidId[source]

Bases: zope.schema._bootstrapinterfaces.ValidationError

The specified id is not valid.

exception zope.schema.interfaces.InvalidDottedName[source]

Bases: zope.schema._bootstrapinterfaces.ValidationError

The specified dotted name is not valid.

exception zope.schema.interfaces.Unbound[source]

Bases: exceptions.Exception

The field is not bound.

Schema APIs

zope.schema.getFields(schema)[source]

Return a dictionary containing all the Fields in a schema.

zope.schema.getFieldsInOrder(schema, _field_key=<function <lambda>>)[source]

Return a list of (name, value) tuples in native schema order.

zope.schema.getFieldNames(schema)[source]

Return a list of all the Field names in a schema.

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.IField members of the schema are validated after being bound to value. (Note that we do not check for arbitrary zope.interface.Attribute members 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.Attribute

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')
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.

getDoc()[source]

Returns the documentation for the object.

class zope.schema.Collection(value_type=<Not Given>, unique=<Not Given>, **kw)[source]

Bases: zope.schema._bootstrapfields.MinMaxLen, zope.schema._bootstrapfields.Iterable

A generic collection implementing zope.schema.interfaces.ICollection.

Subclasses can define the attribute value_type to be a field such as an Object that will be checked for each member of the collection. This can then be omitted from the constructor call.

They can also define the attribute _type to 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_type and unique, and allow eliding them from the constructor.

bind(context)[source]

See zope.schema._bootstrapinterfaces.IField.

zope.schema._field.AbstractCollection

An alternate name for Collection.

Deprecated since version 4.6.0: Use Collection instead.

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.IFromBytes

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')
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.

bind(context)[source]

See zope.schema._bootstrapinterfaces.IField.

fromUnicode(value)[source]

See IFromUnicode.

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.Date(min=None, max=None, default=None, **kw)[source]

Field containing a date.

class zope.schema.Datetime(*args, **kw)[source]

Field containing a datetime.

class zope.schema.Dict(key_type=None, value_type=None, **kw)[source]

Bases: zope.schema._field.MutableMapping

A field representing a Dict.

class zope.schema.FrozenSet(*args, **kwargs)[source]
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.MutableSequence

A 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.

bind(object)[source]

See zope.schema._bootstrapinterfaces.IField.

class zope.schema.MutableMapping(key_type=None, value_type=None, **kw)[source]

Bases: zope.schema._field.Mapping

A 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.Sequence

A field representing a mutable sequence.

New in version 4.6.0.

class zope.schema.MinMaxLen(min_length=0, max_length=None, **kw)[source]

Bases: object

Expresses 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 IObject field. The keyword arguments are as for Field.

Changed in version 4.6.0: Add the keyword argument validate_invariants. When true (the default), the schema’s validateInvariants method will be invoked to check the @invariant properties of the schema.

Changed in version 4.6.0: The schema argument can be ommitted in a subclass that specifies a schema attribute.

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: object

Values 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._AbstractSet

A field representing a set.

class zope.schema.Sequence(value_type=<Not Given>, unique=<Not Given>, **kw)[source]

Bases: zope.schema._field.Collection

A field representing an ordered sequence.

New in version 4.6.0.

class zope.schema.Time(min=None, max=None, default=None, **kw)[source]

Field containing a time.

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.Sequence

A 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.

fromUnicode(value)[source]

See IFromUnicode.

class zope.schema.BytesLine(min_length=0, max_length=None, **kw)[source]

A Bytes field with no newlines.

class zope.schema.SourceText(*args, **kw)[source]

Field for source text of object.

class zope.schema.Text(*args, **kw)[source]

A field containing text used for human discourse.

fromUnicode(str)[source]
>>> from zope.schema.interfaces import WrongType
>>> from zope.schema.interfaces import ConstraintNotSatisfied
>>> from zope.schema import Text
>>> from zope.schema._compat import text_type
>>> t = Text(constraint=lambda v: 'x' in v)
>>> t.fromUnicode(b"foo x spam") 
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") 
Traceback (most recent call last):
...
zope.schema._bootstrapinterfaces.ConstraintNotSatisfied: (u'foo spam', '')
class zope.schema.TextLine(*args, **kw)[source]

A text field with no newlines.

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 implements IFromUnicode and IFromBytes.

Changed in version 4.9.0: This is now a distinct type instead of an alias for either Text or Bytes, depending on the platform.

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 implements IFromUnicode and IFromBytes.

Changed in version 4.9.0: This is now a distinct type instead of an alias for either TextLine or BytesLine, depending on the platform.

class zope.schema.Password(*args, **kw)[source]

A text field containing a text used as a password.

set(context, value)[source]

Update the password.

We use a special marker value that a widget can use to tell us that the password didn’t change. This is needed to support edit forms that don’t display the existing password and want to work together with encryption.

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.IFromBytes

Changed 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.Field

A field representing a numbers.Number and implementing zope.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**31234) + '.' + str(2**256)) 
Decimal('234...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**31234) + '.' + str(2**256)).encode('ascii')) 
Decimal('234...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.Number

A field representing a numbers.Complex and implementing zope.schema.interfaces.IComplex.

The fromUnicode() method is like that for Number, 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**31234) + '.' + 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**31234) + '.' + str(2**256)).encode('ascii')) 
inf
>>> 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.

class zope.schema.Real(min=None, max=None, default=None, **kw)[source]

Bases: zope.schema._bootstrapfields.Complex

A field representing a numbers.Real and implementing zope.schema.interfaces.IReal.

The fromUnicode() method is like that for Complex, 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**31234) + '.' + 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.Real

A field representing a numbers.Rational and implementing zope.schema.interfaces.IRational.

The fromUnicode() method is like that for Real, 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**31234) + '.' + str(2**256)) 
Fraction(777..., 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.Rational

A field representing a numbers.Integral and implementing zope.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") 
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.Real

A field representing a native float and implementing zope.schema.interfaces.IFloat.

The class zope.schema.Real is a more general version, accepting floats, integers, and fractions.

The fromUnicode() method only accepts values that can be parsed by the float constructor:

>>> 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**31234) + '.' + 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**31234) + '.' + 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.Integral

A 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.Number

A field representing a native decimal.Decimal and implementing zope.schema.interfaces.IDecimal.

The fromUnicode() method only accepts values that can be parsed by the Decimal constructor:

>>> 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**31234) + '.' + str(2**256)) 
Decimal('2349...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**31234) + '.' + str(2**256)).encode("ascii")) 
Decimal('2349...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: object

Simple 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: object

Vocabulary 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 createTerm(*args)[source]

Create a single term from data.

Subclasses may override this with a class method that creates a term of the appropriate type from the arguments.

getTerm(value)[source]

See zope.schema.interfaces.IBaseVocabulary

getTermByToken(token)[source]

See zope.schema.interfaces.IVocabularyTokenized

class zope.schema.vocabulary.TreeVocabulary(terms, *interfaces)[source]

Bases: object

Vocabulary 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.

keys()[source]

Return the keys of the mapping object.

values()[source]

Return the values of the mapping object.

items()[source]

Return the items of the mapping object.

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 ITitledTokenizedTerm when a title is actually provided.

getTerm(value)[source]

See zope.schema.interfaces.IBaseVocabulary

getTermByToken(token)[source]

See zope.schema.interfaces.IVocabularyTokenized

getTermPath(value)[source]

Returns a list of strings representing the path from the root node to the node with the given value in the tree.

Returns an empty string if no node has that value.

exception zope.schema.vocabulary.VocabularyRegistryError(name)[source]

Bases: exceptions.LookupError

A specialized subclass of LookupError raised for unknown (unregistered) vocabularies.

class zope.schema.vocabulary.VocabularyRegistry[source]

Bases: object

Default implementation of zope.schema.interfaces.IVocabularyRegistry.

An instance of this class is used by default by getVocabularyRegistry(), which in turn is used by Choice fields.

Named vocabularies must be manually registered with this object using register(). This associates a vocabulary name with a zope.schema.interfaces.IVocabularyFactory.

An alternative to this is to use the zope.component registry via zope.vocabularyregistry.

get(context, name)[source]

See zope.schema.interfaces.IVocabularyRegistry

register(name, factory)[source]

Register a factory for the vocabulary with the given name.

zope.schema.vocabulary.getVocabularyRegistry()[source]

Return the vocabulary registry.

If the registry has not been created yet, an instance of VocabularyRegistry will be installed and used.

zope.schema.vocabulary.setVocabularyRegistry(registry)[source]

Set the vocabulary registry.

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.

class zope.schema.accessors.FieldReadAccessor(field)[source]

Bases: zope.interface.interface.Method

Field read accessor

class zope.schema.accessors.FieldWriteAccessor(field)[source]

Bases: zope.interface.interface.Method

zope.schema.accessors.accessors(field)[source]