[PEAK] 'Categories' in Python

Andy Gross andy at andygross.org
Fri Dec 10 16:30:15 EST 2004


Hi All,

I was playing around with decorators and metaclasses last night, and I 
threw together a quick implementation of Objective-C style "Categories" 
for Python.  In a nutshell, Categories are classes without data 
members, just methods.
I have a bunch of application-specific classes that suffer from 
creeping Mixins - I have to implement some subject-oriented 
functionality to a bunch of related classes, so I originally used 
several Mixins to achieve this.  The result just doesn't feel right, 
and the existence extra base classes gets in the way from time to time. 
  Furthermore, if users need to change some relatively simple behavior, 
they have to dig into the code, find the Mixins, change them, and hope 
things don't break.

My little experiment last night uses a Category metaclass and 
decorators to formalize and simplify this kind of class extension.  An 
overly simple example:

class StringyThings(Category):
	def toLower(self):
		return self.string.lower()

class StringyThing(B1, B2, ... BN):
	@categories(StringyThings)
	def __init__(self, string):
		self.string = string

@category(StringyThings):
def toUpper(self):
	return self.string.upper()

By defining that toUpper function, any class belonging to StringyThings 
(and its subclasses) gains a toUpper method.

For my application, I'm thinking of adding some kind of 
getCategoryForInterface(IFoo) to build dynamic event handler classes
from user defined functions.

I was hoping the wizards here could offer some comments or suggestions. 
  You can see/download the code at:

http://argv0.net/pycategories


/arg




More information about the PEAK mailing list