zope.container

https://travis-ci.org/zopefoundation/zope.container.png?branch=master Documentation Status

This package define interfaces of container components, and provides container implementations such as a BTreeContainer and OrderedContainer, as well as the base class used by zope.site.folder for the Folder implementation.

Contents:

Using zope.container

Containment constraints

Containment constraints allow us to express restrictions on the types of items that can be placed in containers or on the types of containers an item can be placed in. We express these constraints in interfaces. We will use some container and item interfaces defined in zope.container.tests.constraints_example:

from zope.interface import implementer
from zope.location.interfaces import IContained

from zope.container.interfaces import IContainer
from zope.container.constraints import containers
from zope.container.constraints import contains

class IBuddyFolder(IContainer):
    contains('.IBuddy')

In this example, we used the contains function to declare that objects that provide IBuddyFolder can only contain items that provide IBuddy. Note that we used a string containing a dotted name for the IBuddy interface. This is because IBuddy hasn’t been defined yet. When we define IBuddy, we can use IBuddyFolder directly:

class IBuddy(IContained):
    containers(IBuddyFolder)

Now, with these interfaces in place, we can define Buddy and BuddyFolder classes:

@implementer(IBuddy)
class Buddy:
    pass

@implementer(IBuddyFolder)
class BuddyFolder:
    pass

and verify that we can put buddies in buddy folders:

>>> from zope.component.factory import Factory
>>> from zope.container.constraints import checkFactory
>>> from zope.container.constraints import checkObject
>>> from zope.container.tests.constraints_example import Buddy
>>> from zope.container.tests.constraints_example import BuddyFolder

>>> checkObject(BuddyFolder(), 'x', Buddy())
>>> checkFactory(BuddyFolder(), 'x', Factory(Buddy))
True

If we try to use other containers or folders, we’ll get errors:

>>> from zope.container.interfaces import IContainer
>>> from zope.interface import implementer
>>> @implementer(IContainer)
... class Container:
...     pass

>>> from zope.location.interfaces import IContained
>>> @implementer(IContained)
... class Contained:
...     pass

>>> checkObject(Container(), 'x', Buddy())
... 
Traceback (most recent call last):
InvalidContainerType: ...

>>> checkFactory(Container(), 'x', Factory(Buddy))
False

>>> checkObject(BuddyFolder(), 'x', Contained())
... 
Traceback (most recent call last):
InvalidItemType: ...

>>> checkFactory(BuddyFolder(), 'x', Factory(Contained))
False

In the example, we defined the container first and then the items. We could have defined these in the opposite order:

class IContact(IContained):
    containers('.IContacts')

class IContacts(IContainer):
    contains(IContact)

@implementer(IContact)
class Contact:
    pass

@implementer(IContacts)
class Contacts:
    pass
>>> from zope.container.tests.constraints_example import Contact
>>> from zope.container.tests.constraints_example import Contacts
>>> checkObject(Contacts(), 'x', Contact())

>>> checkFactory(Contacts(), 'x', Factory(Contact))
True

>>> checkObject(Contacts(), 'x', Buddy())
... 
Traceback (most recent call last):
InvalidItemType: ...

>>> checkFactory(Contacts(), 'x', Factory(Buddy))
False

The constraints prevent us from moving a container beneath itself (either into itself or another folder beneath it):

>>> container = Container()
>>> checkObject(container, 'x', container)
Traceback (most recent call last):
TypeError: Cannot add an object to itself or its children.

>>> from zope.interface import directlyProvides
>>> from zope.location.interfaces import ILocation
>>> subcontainer = Container()
>>> directlyProvides(subcontainer, ILocation)
>>> subcontainer.__parent__ = container
>>> checkObject(subcontainer, 'x', container)
Traceback (most recent call last):
TypeError: Cannot add an object to itself or its children.

zope.container API

Interfaces

Container-related interfaces

exception zope.container.interfaces.ContainerError[source]

Bases: exceptions.Exception

An error of a container with one of its components.

interface zope.container.interfaces.IBTreeContainer[source]

Extends: zope.container.interfaces.IContainer

Container that supports BTree semantics for some methods.

keys(key=None)

Return an iterator over the keys in the container.

If None is passed as key, this method behaves as if no argument were passed; exactly as required for IContainer.keys().

If key is in the container, the first key provided by the iterator will be that key. Otherwise, the first key will be the one that would come next if key were in the container.

items(key=None)

Return an iterator over the key-value pairs in the container.

If None is passed as key, this method behaves as if no argument were passed; exactly as required for IContainer.items().

If key is in the container, the first item provided by the iterator will correspond to that key. Otherwise, the first item will be for the key that would come next if key were in the container.

values(key=None)

Return an iterator over the values in the container.

If None is passed as key, this method behaves as if no argument were passed; exactly as required for IContainer.values().

If key is in the container, the first value provided by the iterator will correspond to that key. Otherwise, the first value will be for the key that would come next if key were in the container.

interface zope.container.interfaces.IContainer[source]

Extends: zope.container.interfaces.IReadContainer, zope.container.interfaces.IWriteContainer

Readable and writable content container.

interface zope.container.interfaces.IContainerModifiedEvent[source]

Extends: zope.lifecycleevent.interfaces.IObjectModifiedEvent

The container has been modified.

This event is specific to “containerness” modifications, which means addition, removal or reordering of sub-objects.

interface zope.container.interfaces.IContainerNamesContainer[source]

Extends: zope.container.interfaces.IContainer

Containers that always choose names for their items.

interface zope.container.interfaces.IContentContainer[source]

Extends: zope.container.interfaces.IContainer

A container that is to be used as a content type.

interface zope.container.interfaces.IFind[source]

Find support for containers.

find(id_filters=None, object_filters=None)

Find object that matches all filters in all sub-objects.

This container itself is not included.

interface zope.container.interfaces.IItemContainer[source]

Extends: zope.interface.common.mapping.IItemMapping

Minimal readable container.

interface zope.container.interfaces.IItemWriteContainer[source]

Extends: zope.container.interfaces.IWriteContainer, zope.container.interfaces.IItemContainer

A write container that also supports minimal reads.

interface zope.container.interfaces.IOrdered[source]

Objects whose contents are maintained in order.

updateOrder(order)

Revise the order of keys, replacing the current ordering.

order is a list or a tuple containing the set of existing keys in the new order. order must contain len(keys()) items and cannot contain duplicate keys.

Raises TypeError if order is not a tuple or a list.

Raises ValueError if order contains an invalid set of keys.

interface zope.container.interfaces.IOrderedContainer[source]

Extends: zope.container.interfaces.IOrdered, zope.container.interfaces.IContainer

Containers whose contents are maintained in order.

interface zope.container.interfaces.IReadContainer[source]

Extends: zope.container.interfaces.ISimpleReadContainer, zope.interface.common.mapping.IEnumerableMapping

Readable containers that can be enumerated.

interface zope.container.interfaces.IReservedNames[source]

A sequence of names that are reserved for that container

reservedNames

Reserved Names

Names that are not allowed for addable content

interface zope.container.interfaces.ISimpleReadContainer[source]

Extends: zope.container.interfaces.IItemContainer, zope.interface.common.mapping.IReadMapping

Readable content containers.

interface zope.container.interfaces.IWriteContainer[source]

An interface for the write aspects of a container.

__setitem__(name, object)

Add the given object to the container under the given name.

Raises a TypeError if the key is not a unicode or ascii string.

Raises a ValueError if the key is empty, or if the key contains a character which is not allowed in an object name.

Raises a KeyError if the key violates a uniqueness constraint.

The container might choose to add a different object than the one passed to this method.

If the object doesn’t implement IContained, then one of two things must be done:

  1. If the object implements ILocation, then the IContained interface must be declared for the object.
  2. Otherwise, a ContainedProxy is created for the object and stored.

The object’s __parent__ and __name__ attributes are set to the container and the given name.

If the old parent was None, then an IObjectAddedEvent is generated, otherwise, an IObjectMovedEvent is generated. An IContainerModifiedEvent is generated for the container.

If the object replaces another object, then the old object is deleted before the new object is added, unless the container vetos the replacement by raising an exception.

If the object’s __parent__ and __name__ were already set to the container and the name, then no events are generated and no hooks. This allows advanced clients to take over event generation.

__delitem__(name)

Delete the named object from the container.

Raises a KeyError if the object is not found.

If the deleted object’s __parent__ and __name__ match the container and given name, then an IObjectRemovedEvent is generated and the attributes are set to None. If the object can be adapted to IObjectMovedEvent, then the adapter’s moveNotify method is called with the event.

Unless the object’s __parent__ and __name__ attributes were initially None, generate an IContainerModifiedEvent for the container.

If the object’s __parent__ and __name__ were already set to None, then no events are generated. This allows advanced clients to take over event generation.

exception zope.container.interfaces.InvalidContainerType[source]

Bases: zope.interface.exceptions.Invalid, exceptions.TypeError

The type of a container is not valid.

exception zope.container.interfaces.InvalidItemType[source]

Bases: zope.interface.exceptions.Invalid, exceptions.TypeError

The type of an item is not valid.

exception zope.container.interfaces.InvalidType[source]

Bases: zope.interface.exceptions.Invalid, exceptions.TypeError

The type of an object is not valid.

exception zope.container.interfaces.NameReserved[source]

Bases: exceptions.ValueError

The name is reserved for this container

exception zope.container.interfaces.UnaddableError(container, obj, message='')[source]

Bases: zope.container.interfaces.ContainerError

An object cannot be added to a container.

Implementations

Bases and Events

Classes to support implementing IContained

class zope.container.contained.Contained[source]

Bases: object

Stupid mix-in that defines __parent__ and __name__ attributes

class zope.container.contained.ContainerModifiedEvent(object, *descriptions)[source]

Bases: zope.lifecycleevent.ObjectModifiedEvent

The container has been modified.

Init with a list of modification descriptions.

class zope.container.contained.ContainerSublocations(container)[source]

Bases: object

Get the sublocations for a container

Obviously, this is the container values:

>>> class MyContainer(object):
...     def __init__(self, **data):
...         self.data = data
...     def __iter__(self):
...         return iter(self.data)
...     def __getitem__(self, key):
...         return self.data[key]
>>> container = MyContainer(x=1, y=2, z=42)
>>> adapter = ContainerSublocations(container)
>>> sublocations = list(adapter.sublocations())
>>> sublocations.sort()
>>> sublocations
[1, 2, 42]
class zope.container.contained.DecoratedSecurityCheckerDescriptor[source]

Bases: object

Descriptor for a Decorator that provides a decorated security checker.

class zope.container.contained.DecoratorSpecificationDescriptor[source]

Bases: _interface_coptimizations.ObjectSpecificationDescriptor

Support for interface declarations on decorators

>>> from zope.interface import *
>>> class I1(Interface):
...     pass
>>> class I2(Interface):
...     pass
>>> class I3(Interface):
...     pass
>>> class I4(Interface):
...     pass
>>> @implementer(I1)
... class D1(ContainedProxy):
...   pass
>>> @implementer(I2)
... class D2(ContainedProxy):
...   pass
>>> @implementer(I3)
... class X:
...   pass
>>> x = X()
>>> directlyProvides(x, I4)

Interfaces of X are ordered with the directly-provided interfaces first

>>> [interface.getName() for interface in list(providedBy(x))]
['I4', 'I3']

When we decorate objects, what order should the interfaces come in? One could argue that decorators are less specific, so they should come last.

>>> [interface.getName() for interface in list(providedBy(D1(x)))]
['I4', 'I3', 'I1', 'IContained', 'IPersistent']
>>> [interface.getName() for interface in list(providedBy(D2(D1(x))))]
['I4', 'I3', 'I1', 'IContained', 'IPersistent', 'I2']
zope.container.contained.contained(object, container, name=None)[source]

Establish the containment of the object in the container

Just return the contained object without an event. This is a convenience “macro” for:

containedEvent(object, container, name)[0]

This function is only used for tests.

zope.container.contained.containedEvent(object, container, name=None)[source]

Establish the containment of the object in the container

The object and necessary event are returned. The object may be a ContainedProxy around the original object. The event is an added event, a moved event, or None.

If the object implements IContained, simply set its __parent__ and __name__ attributes:

>>> container = {}
>>> item = Contained()
>>> x, event = containedEvent(item, container, u'foo')
>>> x is item
True
>>> item.__parent__ is container
True
>>> item.__name__
u'foo'

We have an added event:

>>> event.__class__.__name__
'ObjectAddedEvent'
>>> event.object is item
True
>>> event.newParent is container
True
>>> event.newName
u'foo'
>>> event.oldParent
>>> event.oldName

Now if we call contained again:

>>> x2, event = containedEvent(item, container, u'foo')
>>> x2 is item
True
>>> item.__parent__ is container
True
>>> item.__name__
u'foo'

We don’t get a new added event:

>>> event

If the object already had a parent but the parent or name was different, we get a moved event:

>>> x, event = containedEvent(item, container, u'foo2')
>>> event.__class__.__name__
'ObjectMovedEvent'
>>> event.object is item
True
>>> event.newParent is container
True
>>> event.newName
u'foo2'
>>> event.oldParent is container
True
>>> event.oldName
u'foo'

If the object implements ILocation, but not IContained, set its __parent__ and __name__ attributes and declare that it implements IContained:

>>> from zope.location import Location
>>> item = Location()
>>> IContained.providedBy(item)
False
>>> x, event = containedEvent(item, container, 'foo')
>>> x is item
True
>>> item.__parent__ is container
True
>>> item.__name__
'foo'
>>> IContained.providedBy(item)
True

If the object doesn’t even implement ILocation, put a ContainedProxy around it:

>>> item = []
>>> x, event = containedEvent(item, container, 'foo')
>>> x is item
False
>>> x.__parent__ is container
True
>>> x.__name__
'foo'

Make sure we don’t lose existing directly provided interfaces.

>>> from zope.interface import Interface, directlyProvides
>>> class IOther(Interface):
...     pass
>>> from zope.location import Location
>>> item = Location()
>>> directlyProvides(item, IOther)
>>> IOther.providedBy(item)
True
>>> x, event = containedEvent(item, container, 'foo')
>>> IOther.providedBy(item)
True
zope.container.contained.dispatchToSublocations(object, event)[source]

Dispatch an event to sublocations of a given object

When a move event happens for an object, it’s important to notify subobjects as well.

We do this based on locations.

Suppose, for example, that we define some location objects.

>>> @zope.interface.implementer(ILocation)
... class L(object):
...     def __init__(self, name):
...         self.__name__ = name
...         self.__parent__ = None
...     def __repr__(self):
...         return '%s(%s)' % (
...                 self.__class__.__name__, str(self.__name__))
>>> @zope.interface.implementer(ISublocations)
... class C(L):
...     def __init__(self, name, *subs):
...         L.__init__(self, name)
...         self.subs = subs
...         for sub in subs:
...             sub.__parent__ = self
...     def sublocations(self):
...         return self.subs
>>> c = C(1,
...       C(11,
...         L(111),
...         L(112),
...         ),
...       C(12,
...         L(121),
...         L(122),
...         L(123),
...         L(124),
...         ),
...       L(13),
...       )

Now, if we call the dispatcher, it should call event handlers for all of the objects.

Lets create an event handler that records the objects it sees:

>>> seen = []
>>> def handler(ob, event):
...     seen.append((ob, event.object))

Note that we record the the object the handler is called on as well as the event object:

Now we’ll register it:

>>> from zope import component
>>> from zope.lifecycleevent.interfaces import IObjectMovedEvent
>>> component.provideHandler(handler, [None, IObjectMovedEvent])

We also register our dispatcher:

>>> component.provideHandler(dispatchToSublocations,
...   [None, IObjectMovedEvent])

We can then call the dispatcher for the root object:

>>> event = ObjectRemovedEvent(c)
>>> dispatchToSublocations(c, event)

Now, we should have seen all of the subobjects:

>>> seenreprs = sorted(map(repr, seen))
>>> seenreprs
['(C(11), C(1))', '(C(12), C(1))', '(L(111), C(1))', '(L(112), C(1))', '(L(121), C(1))', '(L(122), C(1))', '(L(123), C(1))', '(L(124), C(1))', '(L(13), C(1))']

We see that we get entries for each of the subobjects and that,for each entry, the event object is top object.

This suggests that location event handlers need to be aware that the objects they are called on and the event objects could be different.

zope.container.contained.notifyContainerModified(object, *descriptions)[source]

Notify that the container was modified.

zope.container.contained.setitem(container, setitemf, name, object)[source]

Helper function to set an item and generate needed events

This helper is needed, in part, because the events need to get published after the object has been added to the container.

If the item implements IContained, simply set its __parent__ and __name__ attributes:

>>> class IItem(zope.interface.Interface):
...     pass
>>> @zope.interface.implementer(IItem)
... class Item(Contained):
...     def setAdded(self, event):
...         self.added = event
...     def setMoved(self, event):
...         self.moved = event
>>> from zope.lifecycleevent.interfaces import IObjectAddedEvent
>>> from zope.lifecycleevent.interfaces import IObjectMovedEvent
>>> from zope import component
>>> component.provideHandler(lambda obj, event: obj.setAdded(event),
...   [IItem, IObjectAddedEvent])
>>> component.provideHandler(lambda obj, event: obj.setMoved(event),
...   [IItem, IObjectMovedEvent])
>>> item = Item()
>>> container = {}
>>> setitem(container, container.__setitem__, u'c', item)
>>> container[u'c'] is item
1
>>> item.__parent__ is container
1
>>> item.__name__
u'c'

If we run this using the testing framework, we’ll use getEvents to track the events generated:

>>> from zope.component.eventtesting import getEvents
>>> from zope.lifecycleevent.interfaces import IObjectModifiedEvent

We have an added event:

>>> len(getEvents(IObjectAddedEvent))
1
>>> event = getEvents(IObjectAddedEvent)[-1]
>>> event.object is item
1
>>> event.newParent is container
1
>>> event.newName
u'c'
>>> event.oldParent
>>> event.oldName

As well as a modification event for the container:

>>> len(getEvents(IObjectModifiedEvent))
1
>>> getEvents(IObjectModifiedEvent)[-1].object is container
1

The item’s hooks have been called:

>>> item.added is event
1
>>> item.moved is event
1

We can suppress events and hooks by setting the __parent__ and __name__ first:

>>> item = Item()
>>> item.__parent__, item.__name__ = container, 'c2'
>>> setitem(container, container.__setitem__, u'c2', item)
>>> len(container)
2
>>> len(getEvents(IObjectAddedEvent))
1
>>> len(getEvents(IObjectModifiedEvent))
1
>>> getattr(item, 'added', None)
>>> getattr(item, 'moved', None)

If the item had a parent or name (as in a move or rename), we generate a move event, rather than an add event:

>>> setitem(container, container.__setitem__, u'c3', item)
>>> len(container)
3
>>> len(getEvents(IObjectAddedEvent))
1
>>> len(getEvents(IObjectModifiedEvent))
2
>>> len(getEvents(IObjectMovedEvent))
2

(Note that we have 2 move events because add are move events.)

We also get the move hook called, but not the add hook:

>>> event = getEvents(IObjectMovedEvent)[-1]
>>> getattr(item, 'added', None)
>>> item.moved is event
1

If we try to replace an item without deleting it first, we’ll get an error:

>>> setitem(container, container.__setitem__, u'c', [])
Traceback (most recent call last):
...
KeyError: u'c'
>>> del container[u'c']
>>> setitem(container, container.__setitem__, u'c', [])
>>> len(getEvents(IObjectAddedEvent))
2
>>> len(getEvents(IObjectModifiedEvent))
3

If the object implements ILocation, but not IContained, set it’s __parent__ and __name__ attributes and declare that it implements IContained:

>>> from zope.location import Location
>>> item = Location()
>>> IContained.providedBy(item)
0
>>> setitem(container, container.__setitem__, u'l', item)
>>> container[u'l'] is item
1
>>> item.__parent__ is container
1
>>> item.__name__
u'l'
>>> IContained.providedBy(item)
1

We get new added and modification events:

>>> len(getEvents(IObjectAddedEvent))
3
>>> len(getEvents(IObjectModifiedEvent))
4

If the object doesn’t even implement ILocation, put a ContainedProxy around it:

>>> item = []
>>> setitem(container, container.__setitem__, u'i', item)
>>> container[u'i']
[]
>>> container[u'i'] is item
0
>>> item = container[u'i']
>>> item.__parent__ is container
1
>>> item.__name__
u'i'
>>> IContained.providedBy(item)
1
>>> len(getEvents(IObjectAddedEvent))
4
>>> len(getEvents(IObjectModifiedEvent))
5

We’ll get type errors if we give keys that aren’t unicode or ascii keys:

>>> setitem(container, container.__setitem__, 42, item)
Traceback (most recent call last):
...
TypeError: name not unicode or ascii string
>>> setitem(container, container.__setitem__, None, item)
Traceback (most recent call last):
...
TypeError: name not unicode or ascii string
>>> c = bytes([200]) if PY3 else chr(200)
>>> setitem(container, container.__setitem__, b'hello ' + c, item)
Traceback (most recent call last):
...
TypeError: name not unicode or ascii string

and we’ll get a value error of we give an empty string or unicode:

>>> setitem(container, container.__setitem__, '', item)
Traceback (most recent call last):
...
ValueError: empty names are not allowed
>>> setitem(container, container.__setitem__, u'', item)
Traceback (most recent call last):
...
ValueError: empty names are not allowed
zope.container.contained.uncontained(object, container, name=None)[source]

Clear the containment relationship between the object and the container.

If we run this using the testing framework, we’ll use getEvents to track the events generated:

>>> from zope.component.eventtesting import getEvents
>>> from zope.lifecycleevent.interfaces import IObjectModifiedEvent
>>> from zope.lifecycleevent.interfaces import IObjectRemovedEvent

We’ll start by creating a container with an item:

>>> class Item(Contained):
...     pass
>>> item = Item()
>>> container = {u'foo': item}
>>> x, event = containedEvent(item, container, u'foo')
>>> item.__parent__ is container
1
>>> item.__name__
u'foo'

Now we’ll remove the item. It’s parent and name are cleared:

>>> uncontained(item, container, u'foo')
>>> item.__parent__
>>> item.__name__

We now have a new removed event:

>>> len(getEvents(IObjectRemovedEvent))
1
>>> event = getEvents(IObjectRemovedEvent)[-1]
>>> event.object is item
1
>>> event.oldParent is container
1
>>> event.oldName
u'foo'
>>> event.newParent
>>> event.newName

As well as a modification event for the container:

>>> len(getEvents(IObjectModifiedEvent))
1
>>> getEvents(IObjectModifiedEvent)[-1].object is container
1

Now if we call uncontained again:

>>> uncontained(item, container, u'foo')

We won’t get any new events, because __parent__ and __name__ are None:

>>> len(getEvents(IObjectRemovedEvent))
1
>>> len(getEvents(IObjectModifiedEvent))
1

But, if either the name or parent are not None and they are not the container and the old name, we’ll get a modified event but not a removed event.

>>> item.__parent__, item.__name__ = container, None
>>> uncontained(item, container, u'foo')
>>> len(getEvents(IObjectRemovedEvent))
1
>>> len(getEvents(IObjectModifiedEvent))
2
>>> item.__parent__, item.__name__ = None, u'bar'
>>> uncontained(item, container, u'foo')
>>> len(getEvents(IObjectRemovedEvent))
1
>>> len(getEvents(IObjectModifiedEvent))
3

If one tries to delete a Broken object, we allow them to do just that.

>>> class Broken(object):
...     __Broken_state__ = {}
>>> broken = Broken()
>>> broken.__Broken_state__['__name__'] = u'bar'
>>> broken.__Broken_state__['__parent__'] = container
>>> container[u'bar'] = broken
>>> uncontained(broken, container, u'bar')
>>> len(getEvents(IObjectRemovedEvent))
2

BTree

This module provides a sample btree container implementation.

class zope.container.btree.BTreeContainer[source]

Bases: zope.container.contained.Contained, persistent.Persistent

OOBTree-based container

get(key, default=None)[source]

See interface IReadContainer

has_key(key)

See interface IReadContainer

Directory

File-system representation adapters for containers

This module includes two adapters (adapter factories, really) for providing a file-system representation for containers:

noop
Factory that “adapts” IContainer to IWriteDirectory. This is a lie, since it just returns the original object.
Cloner
An IDirectoryFactory adapter that just clones the original object.
class zope.container.directory.Cloner(context)[source]

Bases: object

IContainer to zope.filerepresentation.interfaces.IDirectoryFactory adapter that clones.

This adapter provides a factory that creates a new empty container of the same class as it’s context.

class zope.container.directory.ReadDirectory(context)[source]

Bases: object

Adapter to provide a file-system rendition of folders.

zope.container.directory.noop(container)[source]

Adapt an IContainer to an IWriteDirectory by just returning it

This “works” because IContainer and IWriteDirectory have the same methods, however, the output doesn’t actually implement IWriteDirectory.

Folders

The standard Zope Folder.

class zope.container.folder.Folder[source]

Bases: zope.container.btree.BTreeContainer

The standard Zope Folder implementation.

Find Support

class zope.container.find.FindAdapter(context)[source]

Bases: object

Adapts zope.container.interfaces.IReadContainer

find(id_filters=None, object_filters=None)[source]

See IFind

class zope.container.find.SimpleIdFindFilter(ids)[source]

Bases: object

Filter objects by ID

matches(id)[source]

See INameFindFilter

class zope.container.find.SimpleInterfacesFindFilter(*interfaces)[source]

Bases: object

Filter objects on the provided interfaces

Ordered

Ordered container implementation.

class zope.container.ordered.OrderedContainer[source]

Bases: persistent.Persistent, zope.container.contained.Contained

OrderedContainer maintains entries’ order as added and moved.

>>> oc = OrderedContainer()
>>> int(IOrderedContainer.providedBy(oc))
1
>>> len(oc)
0
get(key, default=None)[source]

See IOrderedContainer.

>>> oc = OrderedContainer()
>>> oc['foo'] = 'bar'
>>> oc.get('foo')
'bar'
>>> oc.get('funky', 'No chance, dude.')
'No chance, dude.'
has_key(key)

See IOrderedContainer.

>>> oc = OrderedContainer()
>>> oc['foo'] = 'bar'
>>> int('foo' in oc)
1
>>> int('quux' in oc)
0
items()[source]

See IOrderedContainer.

>>> oc = OrderedContainer()
>>> oc.keys()
[]
>>> oc['foo'] = 'bar'
>>> oc.items()
[('foo', 'bar')]
>>> oc['baz'] = 'quux'
>>> oc.items()
[('foo', 'bar'), ('baz', 'quux')]
>>> int(len(oc._order) == len(oc._data))
1
keys()[source]

See IOrderedContainer.

>>> oc = OrderedContainer()
>>> oc.keys()
[]
>>> oc['foo'] = 'bar'
>>> oc.keys()
['foo']
>>> oc['baz'] = 'quux'
>>> oc.keys()
['foo', 'baz']
>>> int(len(oc._order) == len(oc._data))
1
updateOrder(order)[source]

See IOrderedContainer.

>>> oc = OrderedContainer()
>>> oc['foo'] = 'bar'
>>> oc['baz'] = 'quux'
>>> oc['zork'] = 'grue'
>>> oc.keys()
['foo', 'baz', 'zork']
>>> oc.updateOrder(['baz', 'foo', 'zork'])
>>> oc.keys()
['baz', 'foo', 'zork']
>>> oc.updateOrder(['baz', 'zork', 'foo'])
>>> oc.keys()
['baz', 'zork', 'foo']
>>> oc.updateOrder(['baz', 'zork', 'foo'])
>>> oc.keys()
['baz', 'zork', 'foo']
>>> oc.updateOrder(('zork', 'foo', 'baz'))
>>> oc.keys()
['zork', 'foo', 'baz']
>>> oc.updateOrder(['baz', 'zork'])
Traceback (most recent call last):
...
ValueError: Incompatible key set.
>>> oc.updateOrder(['foo', 'bar', 'baz', 'quux'])
Traceback (most recent call last):
...
ValueError: Incompatible key set.
>>> oc.updateOrder(1)
Traceback (most recent call last):
...
TypeError: order must be a tuple or a list.
>>> oc.updateOrder('bar')
Traceback (most recent call last):
...
TypeError: order must be a tuple or a list.
>>> oc.updateOrder(['baz', 'zork', 'quux'])
Traceback (most recent call last):
...
ValueError: Incompatible key set.
>>> del oc['baz']
>>> del oc['zork']
>>> del oc['foo']
>>> len(oc)
0
values()[source]

See IOrderedContainer.

>>> oc = OrderedContainer()
>>> oc.keys()
[]
>>> oc['foo'] = 'bar'
>>> oc.values()
['bar']
>>> oc['baz'] = 'quux'
>>> oc.values()
['bar', 'quux']
>>> int(len(oc._order) == len(oc._data))
1

Sample

Sample container implementation.

This is primarily for testing purposes.

It might be useful as a mix-in for some classes, but many classes will need a very different implementation.

class zope.container.sample.SampleContainer[source]

Bases: zope.container.contained.Contained

Sample container implementation suitable for testing.

It is not suitable, directly as a base class unless the subclass overrides _newContainerData to return a persistent mapping object.

get(key, default=None)[source]

See interface IReadContainer

has_key(key)

See interface IReadContainer

items()[source]

See interface IReadContainer

keys()[source]

See interface IReadContainer

values()[source]

See interface IReadContainer

Size

Adapters that give the size of an object.

class zope.container.size.ContainerSized(container)[source]

Bases: object

Implements zope.size.interfaces.ISize for zope.container.interfaces.IReadContainer

sizeForDisplay()[source]

See ISized

sizeForSorting()[source]

See ISized

Traversal

Traversal components for containers

class zope.container.traversal.ContainerTraversable(container)[source]

Bases: object

Traverses containers via getattr and get.

class zope.container.traversal.ContainerTraverser(container, request)[source]

Bases: object

A traverser that knows how to look up objects by name in a container.

browserDefault(request)[source]

See zope.publisher.browser.interfaces.IBrowserPublisher

publishTraverse(request, name)[source]

See zope.publisher.interfaces.IPublishTraverse

class zope.container.traversal.ItemTraverser(container, request)[source]

Bases: zope.container.traversal.ContainerTraverser

A traverser that knows how to look up objects by name in an item container.

publishTraverse(request, name)[source]

See zope.publisher.interfaces.IPublishTraverse

Changes

4.2.0 (unreleased)

  • Add support for Python 3.5.
  • Drop support for Python 2.6.

4.1.0 (2015-05-22)

  • Make zope.container._proxy.PytContainedProxyBase inherit directly from persistent.AbstractProxyBase, removing a bunch of redundant code, and fixing bugs in interaction with pure-Python persistence. See: https://github.com/zopefoundation/zope.container/pull/4
  • Add direct dependencies on zope.proxy and persistent since we import from them; pin them to the versions needed for pure-Python.
  • Drop deprecated BBB imports module, zope.container.dependency.

4.0.0 (2014-03-19)

  • Add support for Python 3.4.
  • Add support for PyPy.

4.0.0a3 (2013-02-28)

  • Restore Folder pickle forward/backward compatibility with version 3.12.0 after making it inherit from BTreeContainer.

4.0.0a2 (2013-02-21)

  • Allow testing without checkouts of unreleased zope.publisher and ZODB.
  • Add Python 3 Trove classifiers.

4.0.0a1 (2013-02-20)

  • Add support for Python 3.3.
  • Make Folder class inherit from BTreeContainer class, so that the IContainer interface does not need to be re-implemented. Added a data attribute for BBB.
  • Replace deprecated zope.component.adapts usage with equivalent zope.component.adapter decorator.
  • Replace deprecated zope.interface.implements usage with equivalent zope.interface.implementer decorator.
  • Drop support for Python 2.4 and 2.5.
  • Send IContainerModifiedEvent after the container is modified (LP#705600).
  • Preserve the original exception traceback in OrderedContainer.__setitem__.
  • Handle Broken Objects more gracefully
  • Fix a bug that made it impossible to store None values in containers (LP#1070719).

3.12.0 (2010-12-14)

  • Fix detection of moving folders into itself or a subfolder of itself. (LP#118088)
  • Fix ZCML-related tests and dependencies.
  • Add zcml extra dependencies.

3.11.1 (2010-04-30)

  • Prefer the standard libraries doctest module to the one from zope.testing.
  • Add compatibility with ZODB3 3.10 by importing the IBroken interface from it directly. Once we can rely on the new ZODB3 version exclusively, we can remove the dependency onto the zope.broken distribution.
  • Never fail if the suggested name is in a wrong type (#227617)
  • checkName first checks the parameter type before the emptiness.

3.11.0 (2009-12-31)

  • Copy two trivial classes from zope.cachedescriptors into this package, which allows us to remove that dependency. We didn’t actually use any caching properties as the dependency suggested.

3.10.1 (2009-12-29)

  • Move zope.copypastemove related tests into that package.
  • Remove no longer used zcml prefix from the configure file.
  • Stop importing DocTestSuite from zope.testing.doctestunit. Fixes compatibility problems with zope.testing 3.8.4.

3.10.0 (2009-12-15)

  • Break testing dependency on zope.app.testing.
  • Break testing dependency on zope.app.dependable by moving the code and tests into that package.
  • Import ISite from zope.component after it was moved there from zope.location.

3.9.1 (2009-10-18)

  • Rerelease 3.9.0 as it had a broken Windows 2.6 egg.
  • Mark this project as part of the ZTK.

3.9.0 (2009-08-28)

  • Previous releases should be versioned 3.9.0 as they are not pure bugfix releases and worth a “feature” release, increasing feature version.

    Packages that depend on any changes introduced in version 3.8.2 or 3.8.3 should depend on version 3.9 or greater.

3.8.3 (2009-08-27)

  • Move IXMLRPCPublisher ZCML registrations for containers from zope.app.publisher.xmlrpc to zope.container for now.

3.8.2 (2009-05-17)

  • Rid ourselves of IContained interface. This interface was moved to zope.location.interfaces. A b/w compat import still exists to keep old code running. Depend on zope.location>=3.5.4.
  • Rid ourselves of the implementations of IObjectMovedEvent, IObjectAddedEvent, IObjectRemovedEvent interfaces and ObjectMovedEvent, ObjectAddedEvent and ObjectRemovedEvent classes. B/w compat imports still exist. All of these were moved to zope.lifecycleevent. Depend on zope.lifecycleevent>=3.5.2.
  • Fix a bug in OrderedContainer where trying to set the value for a key that already exists (duplication error) would actually delete the key from the order, leaving a dangling reference.
  • Partially break dependency on zope.traversing by disusing zope.traversing.api.getPath in favor of using ILocationInfo(object).getPath(). The rest of the runtime dependencies on zope.traversing are currently interface dependencies.
  • Break runtime dependency on zope.app.dependable by using a zcml condition on the subscriber ZCML directive that registers the CheckDependency handler for IObjectRemovedEvent. If zope.app.dependable is not installed, this subscriber will never be registered. zope.app.dependable is now a testing dependency only.

3.8.1 (2009-04-03)

  • Fix misspackaged 3.8.0

3.8.0 (2009-04-03)

  • Change configure.zcml to not depend on zope.app.component. Fixes: https://bugs.launchpad.net/bugs/348329
  • Move the declaration of IOrderedContainer.updateOrder to a new, basic IOrdered interface and let IOrderedContainer inherit it. This allows easier reuse of the declaration.

3.7.2 (2009-03-12)

  • Fix: added missing ComponentLookupError, missing since revision 95429 and missing in last release.
  • Adapt to the move of IDefaultViewName from zope.component.interfaces to zope.publisher.interfaces.
  • Add support for reserved names for containers. To specify reserved names for some container, you need to provide an adapter from the container to the zope.container.interfaces.IReservedNames interface. The default NameChooser is now also aware of reserved names.

3.7.1 (2009-02-05)

  • Raise more “Pythonic” errors from __setitem__, losing the dependency on zope.exceptions:

    o zope.exceptions.DuplicationError -> KeyError

    o zope.exceptions.UserError -> ValueError

  • Move import of IBroken interface to use new zope.broken package, which has no dependencies beyond zope.interface.

  • Make test part pull in the extra test requirements of this package.

  • Split the z3c.recipe.compattest configuration out into a new file, compat.cfg, to reduce the burden of doing standard unit tests.

  • Strip out bogus develop eggs from buildout.cfg.

3.7.0 (2009-01-31)

  • Split this package off zope.app.container. This package is intended to have far less dependencies than zope.app.container.
  • This package also contains the container implementation that used to be in zope.app.folder.

Indices and tables