Zope Annotation

6.0 · active · verified Fri Apr 17

The `zope.annotation` package provides a robust object annotation mechanism, allowing objects to be transparently extended with additional information without modifying their original class. It is part of the Zope Foundation ecosystem, currently at version 6.0, and maintains a stable release cadence aligned with Python and Zope community standards.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to make an arbitrary object annotatable using `directlyProvides(obj, IAnnotatable)` and then use the `IAnnotations` adapter to store and retrieve key-value data on it. This pattern is fundamental for extending objects without inheritance in Zope-based applications.

from zope.interface import directlyProvides
from zope.annotation.interfaces import IAnnotations, IAnnotatable

# Define a simple class that can be annotated
class MyObject:
    pass

# Instantiate the object
obj = MyObject()

# An object must provide IAnnotatable to be annotated.
# In a real Zope application, this might be handled by decorators or base classes.
# For a standalone example, we directly provide the interface.
directlyProvides(obj, IAnnotatable)

# Get the annotations adapter for the object
# If no annotations exist, a new empty dictionary-like object is created.
annotations = IAnnotations(obj)

# Store and retrieve data on the object via annotations
annotations['my_data_key'] = 'This is some data stored as an annotation.'
annotations['another_key'] = {'list': [1, 2, 3], 'dict_val': 'value'}

print(f"Annotation 'my_data_key': {annotations['my_data_key']}")
print(f"Annotation 'another_key': {annotations['another_key']}")

# Check if an annotation exists
if 'my_data_key' in annotations:
    print("'my_data_key' exists in annotations.")

# Delete an annotation
del annotations['my_data_key']

if 'my_data_key' not in annotations:
    print("'my_data_key' successfully deleted.")

view raw JSON →