Zope Size

6.0 · active · verified Fri Apr 17

Zope.size provides interfaces and a simple adapter pattern to determine the 'size' of an object in a generic way, typically for display or aggregation purposes. It is part of the Zope Foundation ecosystem and is currently at version 6.0, receiving updates as part of the broader Zope component set to maintain Python compatibility and address minor issues.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define an object, create an adapter that implements `zope.size.interfaces.ISized` for that object's interface, register the adapter using `zope.component.provideAdapter`, and then retrieve the object's size using the `zope.size.get_size` utility function. It highlights the crucial step of adapter registration.

import zope.interface
import zope.component
from zope.size.interfaces import ISized
from zope.size import get_size

# 1. Define an interface for our object
class IMyObject(zope.interface.Interface):
    """An object with some data."""

# 2. Define a class implementing the interface
@zope.interface.implementer(IMyObject)
class MyObject:
    def __init__(self, items):
        self.items = items

# 3. Define an adapter that provides ISized for IMyObject
@zope.component.adapter(IMyObject)
@zope.interface.implementer(ISized)
class MyObjectSizer:
    def __init__(self, context):
        self.context = context

    @property
    def size(self):
        return len(self.context.items)

# 4. Create an instance of our object
my_list_obj = MyObject([1, 2, 3, 4, 5])
my_dict_obj = MyObject({'a': 1, 'b': 2})

# 5. Register the adapter (typically done at application startup)
zope.component.provideAdapter(MyObjectSizer)

# 6. Use get_size to retrieve the size
list_size = get_size(my_list_obj)
dict_size = get_size(my_dict_obj)

# Print the results
print(f"Size of list object: {list_size}")
print(f"Size of dictionary object: {dict_size}")

# Example of an object without a registered adapter
class UnsizedObject: pass
unsized_obj = UnsizedObject()

try:
    get_size(unsized_obj)
except zope.component.interfaces.ComponentLookupError as e:
    print(f"\nError for unsized object (expected): {e}")

view raw JSON →