adapterzopezope.interface

Can I adapt strings and built-in types in Z


I have an Interface like:

class IRepository(Interface):
    def __init__(path, **options):
        pass

I have implementations of this interface for both Git, and Mercurial. Now I want to write repository-factory that takes a string (the path) and returns an IRepository, by probing if it's a git or hg repository.

However, simply saying:

registerAdapter(repofactory, (str, unicode, ), IRepository)

does not work, cause neither str nor unicode support the IInterface interface.

For now, I'm going with:

registerAdapter(repofactory, (Interface, ), IRepository)

But I would like to know if there are interfaces out there that match only string objects and other Python built-in types.


Solution

  • No, string and unicode objects can't have interfaces. But for this use-case, I'd register named utilities instead and look up the utility by name, or list all utilities available:

    from zope.component import getUtilitiesFor, getUtility
    
    names = [name for name, utility in getUtilitiesFor(IRepository)]
    
    gitrepo = getUtility(IRepository, name='git')