Am Mittwoch, den 05.04.2006, 09:36 -0500 schrieb Jeff Rush:
> I know that Zope3 dropped 'implicit' acquisition, but is there any support 
> for 
> *explicit* acquisition that walks the __parent__ containment hierarchy. 
> Something that follows the same rules as traverse() to look up a name, but 
> from bottom-to-top instead of traverse() from top-to-bottom?
> I know I can roll my own and special case it but I thought I'd ask before I 
> duplicate existing functionality.


for a project we wrote the following function. It climbes up the
conatinment hierachy until it finds an object which implements the given

# Copyright (c) 2005 gocept gmbh & co. kg

def getParentByInterface(obj, interface):
    """Get the first parent of obj which implements interface.

    Parent means an object along the path between object and containment root.
    Returns None if no parent implementing the interface is found.
    Caution: If ojb itself provides interface it is not returned (only parents
             are taken into account.)

    Define some interfaces.

    >>> from zope.interface import Interface, directlyProvides
    >>> class IFace1(Interface):
    ...    pass
    >>> class IFace2(Interface):
    ...    pass

    Create some objects..

    >>> from import setup
    >>> root = setup.buildSampleFolderTree()

    Set the interfaces on some objects.

    >>> directlyProvides(root[u'folder1'], IFace1, IFace2)
    >>> directlyProvides(root[u'folder1'][u'folder1_1'], IFace1)

    Patch Folder to get usable __repr__ strings

    >>> def my_folder_repr(self):
    ...     return '<Folder %s>' % self.__name__
    >>> from import Folder
    >>> Folder.__repr__ = my_folder_repr

    Do testing.

    >>> child = root[u'folder1'][u'folder1_1'][u'folder1_1_2']
    >>> child2 = root[u'folder2'][u'folder2_1'][u'folder2_1_1']

    >>> getParentByInterface(child, IFace1)
    <Folder folder1_1>
    >>> getParentByInterface(child, IFace2)
    <Folder folder1>
    >>> getParentByInterface(getParentByInterface(child, IFace1), IFace1)
    <Folder folder1>
    >>> getParentByInterface(root, IFace1) is None
    >>> getParentByInterface(child2, IFace2) is None
    >>> getParentByInterface(object(), IFace2)
    Traceback (most recent call last):
    AttributeError: 'object' object has no attribute '__parent__'
    for parent in zapi.getParents(obj):
        if interface.providedBy(parent):
            return parent
    return None

Zope3-users mailing list

Reply via email to