[PEAK] 'Categories' in Python

Phillip J. Eby pje at telecommunity.com
Fri Dec 10 19:52:17 EST 2004

At 07:15 PM 12/10/04 -0500, Andy Gross wrote:

>On Dec 10, 2004, at 7:07 PM, Phillip J. Eby wrote:
>>I'm having trouble seeing the benefit, versus just using generic 
>>functions (either single or multi-dispatch).  The only difference between 
>>them and what you're doing as far as I can see is that the calling 
>>signature would be 'toUpper(someObj)' instead of 
>>'someObj.toUpper()'.  But apart from that that, there's not any difference.
>You could be right - I've barely gotten started playing with 
>peak.dispatch, so I might not need this at all.  The idea of categories 
>may be more accessible to some users,  though,

Well, if it's an Objective-C thing, and that's who you're targeting, 
sure.  On the other hand, if you target Lispy or "functional" people, 
they'll be happier with functions.  :)

Functions are also pretty basic to Python, anyway; it's certainly no 
surprise that a module might provide a 'toUpper()' function, and that it 
works if the object it's called on has a 'string' attribute.  The only 
unusual bit is that you can register different algorithms to accomplish the 

So, generic functions+interfaces = your category concept...

class IStringy(Interface):
     string = Attribute("A string")

def toUpper(ob):
     """Return uppercase form of 'ob.string', if it's stringy"""

def toUpper(ob):
     return ob.string.upper()

class SomeStringy:

So, this is really the same thing, except that the interface defines what 
things the categorized object has to have, in order to belong to that 
category.  Alternatively, you can define two interfaces, and write an 
adapter class from one to the other, and then use 
'IUpperable(stringy).toUpper()', for example.

Any or all of these approaches could actually be wrapped in an API that 
hides the interfacish or generic functiony bits, if you so desired.

More information about the PEAK mailing list