pythonzopezope.interfacezope3zope.component

Zope component discrepancy between Interface(obj) and getAdapter(obj, Interface)


What could cause Interface(obj) to return obj, while getAdapter(obj, Interface) returns a properly adapted object?


Solution

  • If a given instance already provides the interface, then IInterface(instance) will return the passed-in instance. After all, it already satisfies the requirement, you can use instance directly if you need to use IInterface methods:

    >>> import zope.interface
    >>> class IFoo(zope.interface.Interface):
    ...     pass
    ... 
    >>> class Foo(object):
    ...     zope.interface.implements(IFoo)
    ...     pass
    ... 
    >>> foo = Foo()
    >>> IFoo(foo)
    <__main__.Foo object at 0x10eed22d0>
    >>> IFoo.providedBy(foo)
    True
    

    getAdapter() goes directly to the adapter registry, and if you registered an adapter for the given class to IInterface then that adapter will be returned. This is somewhat pointless, since the original object already provided the interface, so no adaptation was needed.