Navigation

PyObjC protocol support

Introduction

Apple makes use of both formal and informal protocols in the Cocoa framework.
Formal protocols are those protocols that are implemented using Objective-C
protocols:

@protocolNSFoo<NSSomeProtocol>-(int)doesIt;@end

Conforming to a formal protocol requires the interface of a class to explicitly
declare that it implements that protocol, and the implementation must implement
all required methods of the protocol.

Informal protocols are defined as categories on NSObject with no implementation:

@interfaceNSObject(FooDelegate)-(void)optionalFooDelegateMethod;@end

Conforming to an informal protocol is much like conforming to a protocol in Python,
the class simply implements the methods as documented. In most cases, informal
protocols are comprised entirely of optional methods (i.e. NSApplicationDelegate)
and a check is made (i.e. -[NSObjectrespondsToSelector:]) before sending
the message to the target.

Informal protocols and PyObjC

PyObjC has an explicit representation for informal protocols. This makes
it possible to use the protocol description to provide better error messages and
to automaticly deduce the method signatures for classes that implement an
informal protocol.

Informal protocols are represented using instances of
objc.informal_protocol. Instances of this class are added to
a internal registration in the bridge, and are automaticly used when a new
class is declared. Because of this classes don’t have to declare that they
conform to an informal protocol.

Formal protocols and PyObjC

PyObjC also has an explicit representation for formal protocols.

Formal protocols are represented as instances of objc.formal_protocol.
Unlike informal protocols, it is necessary to explicitly declare
conformance to formal protocols. However, all formal protocols in Cocoa
are also described using objc.informal_protocol objects.

In python 2.x declaring conformance to a formal protocol is done by using
the formal protocol as a mix-in, and by implementing its methods:

And finally, it is also possible to specify the protocols that the class
conforms to using an attribute named __pyobjc_protocols__ in the class body. This
works for both Python 2.x and 3.x, and is primarily meant to be used by code that
needs to work with both language versions.