[PEAK] Adapting based on property

Phillip J. Eby pje at telecommunity.com
Wed Jun 29 09:16:14 EDT 2005


At 07:12 AM 6/29/2005 -0400, Peter Parente wrote:
>I'm guessing what I really need is an adapter factory that does something
>like the following pseudocode:
>
>def accessibleAdapterFactory(obj):
>         # get object role
>         role = obj.Role
>         # look for adapters for given role and type
>         return protocol.registry.findAdapterFor(role=role, type=type(obj))
>
>Is such a thing possible with pyprotocols?

Yes.  One way is to define the adapter function as a generic function 
(using the current CVS HEAD of PyProtocols):

     import dispatch

     @dispatch.generic()
     def createIList(obj):
         """Generic function for adapting Accessible"""

     @createIList.when("obj.Role==ComboBox")
     def createComboBoxAsList(obj):
         return AccessibleComboboxAsList(obj)


>Is there another solution?

Yes; instead of adapting, you can use generic functions to perform 
operations like getLength() directly, e.g.:

     @dispatch.generic()
     def getLength(obj)
         pass

     @getLength.when("obj.Role==ListView")
     def listViewLength(obj):
         return obj.Value

     @getLength.when("obj.Role==ComboBox")
     def comboBoxLength(obj):
         return obj.child['list'].Value

Of course, generic functions will do the check on every call (but using a 
hash table lookup if your obj.Role values are hashable), and adapters need 
only be created once.  There are other tradeoffs regarding code clarity as 
well; sometimes interfaces are clearer for a given use case, sometimes 
generic functions.




More information about the PEAK mailing list