Zope Schema
zope.schema is a Python library that extends zope.interface to provide detailed descriptions of object attributes, known as schemas. It enables defining data models, including field types, constraints, and validation methods, independent of specific storage or form libraries. The current version is 8.1, and it's actively maintained by the Zope Foundation with a release cadence tied to features and breaking changes, typically alongside the broader Zope ecosystem.
Warnings
- breaking Python 2.7, 3.5, 3.6, 3.7, and 3.8 are no longer supported. Version 7.1 dropped support for Python 3.7 and 3.8, while Version 7.0 dropped support for Python 2.7, 3.5, and 3.6. Ensure your environment uses Python 3.9 or newer.
- breaking The `pkg_resources` namespace was replaced with PEP 420 native namespace in version 8.0. This might affect projects that relied on the older namespace packaging mechanism, especially in complex deployment scenarios.
- gotcha In versions 6.1.0 and 6.1.1, the `IBool.required` attribute's default behavior changed and was then fixed. Initially, `Bool` fields implicitly set `required` to `False`. If you explicitly relied on `required=True` for `Bool` fields in these versions, ensure your validation logic accounts for this, or upgrade to a newer version where the fix is applied.
- deprecated The use of `vocabularies` with `Choice` fields was deprecated in Zope 3.2. `iterable` sources were introduced as a simpler alternative. While older usage might still work for compatibility, it's recommended to use sources for new implementations.
- gotcha `zope.schema.Choice` fields, by default, raise `ValueError` for duplicate values or tokens during vocabulary initialization. If you're building vocabularies from potentially non-pristine data and wish to suppress these errors, you must explicitly set `swallow_duplicates=True` during initialization.
Install
-
pip install zope.schema
Imports
- Interface
from zope.interface import Interface
- TextLine
from zope.schema import TextLine
- URI
from zope.schema import URI
- Bool
from zope.schema import Bool
- Choice
from zope.schema import Choice
Quickstart
import zope.interface
import zope.schema
class IBookmark(zope.interface.Interface):
title = zope.schema.TextLine(
title='Title',
description='The title of the bookmark',
required=True
)
url = zope.schema.URI(
title='Bookmark URL',
description='URL of the Bookmark',
required=True
)
@zope.interface.implementer(IBookmark)
class Bookmark(object):
title = None
url = None
bm = Bookmark()
# Example of validation (a common use case)
try:
IBookmark['title'].validate('My Awesome Bookmark')
IBookmark['url'].validate('http://example.com/bookmark')
print("Validation successful!")
except zope.schema.ValidationError as e:
print(f"Validation failed: {e}")