1from objc import _objc
2
3__all__ = ['protocolNamed', 'ProtocolError']
4
5class ProtocolError(_objc.error):
6    __module__ = 'objc'
7
8PROTOCOL_CACHE = {}
9def protocolNamed(name):
10    """
11    Returns a Protocol object for the named protocol. This is the
12    equivalent of @protocol(name) in Objective-C.
13    Raises objc.ProtocolError when the protocol does not exist.
14    """
15    name = unicode(name)
16    try:
17        return PROTOCOL_CACHE[name]
18    except KeyError:
19        pass
20    for p in _objc.protocolsForProcess():
21        pname = p.__name__
22        PROTOCOL_CACHE.setdefault(pname, p)
23        if pname == name:
24            return p
25    for cls in _objc.getClassList():
26        for p in _objc.protocolsForClass(cls):
27            pname = p.__name__
28            PROTOCOL_CACHE.setdefault(pname, p)
29            if pname == name:
30                return p
31    raise ProtocolError("protocol %r does not exist" % (name,), name)
32