简体   繁体   中英

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM