nti.schema.field

Schema fields.

These fields produce better validation errors than the standard zope.schema fields do. All the standard fields are also aliased to be imported from this module.

class Bool(title='', description='', __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

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'☃'.encode('utf-8'))
False
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'☃')
False
class 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.

bind(context)[source]

See zope.schema._bootstrapinterfaces.IField.

fromUnicode(value)[source]

See IFromUnicode.

class Complex(min=None, max=None, default=None, **kw)[source]

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**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'))
...
inf
>>> f.fromBytes(b"not a number")
Traceback (most recent call last):
...
InvalidNumberLiteral: Invalid literal for Decimal: 'not a number'

Added in version 4.6.0.

class Date(min=None, max=None, default=None, **kw)[source]

Field containing a date.

class Datetime(*args, **kw)[source]

Field containing a datetime.

class Decimal(min=None, max=None, default=None, **kw)[source]

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**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
class DecodingValidTextLine(*args, **kw)[source]

A text type that will attempt to decode non-unicode data as UTF-8.

This primarily exists for legacy support (tests and persisted data).

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

A field representing a Dict.

class DictFromObject(*args, **kwargs)[source]

The key_type and value_type must be supporting IFromObject or IFromUnicode or IFromBytes

Changed in version 1.4.0: Subclass zope.schema.Mapping instead of zope.schema.Dict, allowing for any mapping (such as BTrees), not just dicts. However, the validated value is still a dict.

Changed in version 1.9.0: Implementations of zope.schema.interfaces.ICollection (like zope.schema.List) and zope.schema.interfaces.IMapping (like zope.schema.Dict) will automatically be given a fromObject method when used as the value_type of this object if their value_type is an zope.schema.interfaces.IObject (recursively).

class FieldValidationMixin[source]

A field mixin that causes slightly better errors to be created.

class Float(min=None, max=None, default=None, **kw)[source]
class FrozenSet(*args, **kwargs)[source]
class HTTPURL(*args, **kw)[source]

A URI field that ensures and requires its value to be an absolute HTTP/S URL.

fromUnicode(value)[source]
>>> from zope.schema import Text
>>> 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 IndexedIterable(value_type=<Not Given>, unique=<Not Given>, **kw)[source]

An arbitrary (indexable) iterable, not necessarily a list or tuple; either of those would be acceptable at any time (however, so would a string, so be careful. Try ListOrTuple if that’s a problem).

The values may be homogeneous by setting the value_type.

Changed in version 1.4.0: Subclass zope.schema.Sequence instead of zope.schema.List, which adds checking that the value is indeed a sequence.

class Int(min=None, max=None, default=None, **kw)[source]
class Integral(min=None, max=None, default=None, **kw)[source]

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

Added in version 4.6.0.

class Iterable(title='', description='', __name__='', required=True, readonly=False, constraint=None, default=None, defaultFactory=None, missing_value=<Not Given>)[source]
class List(value_type=<Not Given>, unique=<Not Given>, **kw)[source]

A field representing a List.

class ListOrTuple(value_type=<Not Given>, unique=<Not Given>, **kw)[source]

Restrict sequence values specifically to list and tuple.

class ListOrTupleFromObject(*args, **kwargs)[source]

The value_type MUST be a Variant, or more generally, something supporting IFromObject, IFromUnicode or IFromBytes.

Changed in version 1.9.0: Implementations of zope.schema.interfaces.ICollection (like zope.schema.List) and zope.schema.interfaces.IMapping (like zope.schema.Dict) will automatically be given a fromObject method when used as the value_type of this object if their value_type is an zope.schema.interfaces.IObject (recursively).

class Mapping(key_type=None, value_type=None, **kw)[source]

A field representing a mapping.

Added in version 4.6.0.

bind(object)[source]

See zope.schema._bootstrapinterfaces.IField.

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

A field representing a mutable mapping.

Added in version 4.6.0.

class MutableSequence(value_type=<Not Given>, unique=<Not Given>, **kw)[source]

A field representing a mutable sequence.

Added in version 4.6.0.

class Number(min=None, max=None, default=None, **kw)[source]

A field that parses like a float from a string, but accepts any number.

Deprecated since version 1.4.0: Use zope.schema.Number if you really want arbitrary numbers (including fractions and decimals). You probably want zope.schema.Real instead, though.

class Object(schema=<Not Given>, **kw)[source]

Improved zope.schema.Object.

class ObjectLen(sch, min_length=0, max_length=None, **kwargs)[source]

Allows specifying a length for arbitrary object fields (though the objects themselves must support the len function.

class Rational(min=None, max=None, default=None, **kw)[source]

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**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'

Added in version 4.6.0.

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

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**11234) + '.' + str(2**256))
...
inf
>>> f.fromUnicode("not a number")
Traceback (most recent call last):
...
InvalidNumberLiteral: Invalid literal for Decimal: 'not a number'

Added in version 4.6.0.

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

A field representing an ordered sequence.

Added in version 4.6.0.

class Set(*args, **kwargs)[source]

A field representing a set.

class StrippedValidTextLine(*args, **kw)[source]

A text line that strips whitespace from incoming values.

Added in version 1.13.0.

Changed in version 1.13.1: Handle single character values correctly.

fromUnicode(value)[source]
>>> from zope.schema import Text
>>> 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 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")
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 TextLine(*args, **kw)[source]

A text field with no newlines.

class Timedelta(min=None, max=None, default=None, **kw)[source]

Field containing a timedelta.

class Tuple(value_type=<Not Given>, unique=<Not Given>, **kw)[source]

A field representing a Tuple.

class TupleFromObject(*args, **kwargs)[source]

The value_type MUST be a Variant, or more generally, something supporting IFromObject, IFromUnicode or IFromBytes.

When setting through this object, we will automatically convert lists and only lists to tuples (for convenience coming in through JSON).

Changed in version 1.9.0: Implementations of zope.schema.interfaces.ICollection (like zope.schema.List) and zope.schema.interfaces.IMapping (like zope.schema.Dict) will automatically be given a fromObject method when used as the value_type of this object if their value_type is an zope.schema.interfaces.IObject (recursively).

class UniqueIterable(*args, **kwargs)[source]

An arbitrary iterable, not necessarily an actual set object, but one whose contents are unique. Use this when you can return a set, frozenset or empty tuple. These should be sequences that suport the in operator.

Changed in version 1.5.0: Implement IFromObject.

Changed in version 1.9.0: Implementations of zope.schema.interfaces.ICollection (like zope.schema.List) and zope.schema.interfaces.IMapping (like zope.schema.Dict) will automatically be given a fromObject method when used as the value_type of this object if their value_type is an zope.schema.interfaces.IObject (recursively).

class ValidBytes(min_length=0, max_length=None, **kw)[source]
class ValidBytesLine(min_length=0, max_length=None, **kw)[source]
class ValidChoice(values=None, vocabulary=None, source=None, **kw)[source]
class ValidDatetime(*args, **kw)[source]

Unlike the standard datetime, this will check that the given object is an instance of IDatetime, and raise the same error as object does.

schema = <InterfaceClass zope.interface.common.idatetime.IDateTime>
ValidRegEx

alias of ValidRegularExpression

class ValidRegularExpression(pattern, flags=re.IGNORECASE | re.UNICODE | re.MULTILINE, *args, **kwargs)[source]
class ValidSet(*args, **kwargs)[source]

A set that is validated.

Changed in version 1.5.0: Implement IFromObject.

Changed in version 1.9.0: Implementations of zope.schema.interfaces.ICollection (like zope.schema.List) and zope.schema.interfaces.IMapping (like zope.schema.Dict) will automatically be given a fromObject method when used as the value_type of this object if their value_type is an zope.schema.interfaces.IObject (recursively).

class ValidText(*args, **kw)[source]

A text line that produces slightly better error messages. They will all have the ‘field’ property.

We also fire IBeforeTextAssignedEvent, which the normal mechanism does not.

class ValidTextLine(*args, **kw)[source]

A text line that produces slightly better error messages. They will all have the ‘field’ property.

We also fire IBeforeTextLineAssignedEvent, which the normal mechanism does not.

class ValidURI(*args, **kw)[source]
class Variant(fields, variant_raise_when_schema_provided=False, **kwargs)[source]

Similar to zope.schema.Object, but accepts one of many non-overlapping interfaces.

Changed in version 1.9.0: Implementations of zope.schema.interfaces.ICollection (like zope.schema.List) and zope.schema.interfaces.IMapping (like zope.schema.Dict) will automatically be given a fromObject method when they are used as a field of this object if their value_type is an zope.schema.interfaces.IObject (recursively).

Changed in version 1.16.0: If one of the fields of the variant is (recursively) a IMapping such as a Dict, both the key and value type must be specified. Previously, if they were left None, a validation-time AttributeError would be raised. Now, constructing the variant will raise a RequiredMissing.

fromObject(obj)[source]

Similar to fromUnicode, attempts to turn the given object into something acceptable and valid for this field. Raises a VariantValidationError if this isn’t possible. Adaptation is attempted in the order in which fields were given to the constructor. Some fields cannot be used to adapt.

Changed in version 1.8.0: Raise VariantValidationError instead of whatever last error we got.

Changed in version 1.9.1: Respect self.missing_value and don’t raise an exception if it is passed to this method and we’re not required.

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.

Added in version 4.6.0.