[PEAK] 'Categories' in Python

Andy Gross andy at andygross.org
Fri Dec 10 18:48:42 EST 2004


On Dec 10, 2004, at 6:35 PM, Bob Ippolito wrote:

> There's nothing about categories that prevent them from manipulating 
> data members of the class!  Why does it require the consent of the 
> class?  When you define a category, you are literally extending the 
> class in such a way that it indistinguishable from if you had defined 
> it on the class in the first place.

I guess I'm thinking of it as an analog of interfaces, except for 
providing an implementation of an informal protocol, instead of just 
the protocol specification.  Explicitly declaring consent is just a way 
of formalizing things and perhaps providing a hook for safety-checking.

> Objective-C's rules are that whoever gets there last wins.  Of course, 
> when most of your categories are defined statically, "last" is 
> somewhat unpredictable, that is why they say the behavior is 
> undefined.  It's frowned upon to override methods that are already 
> implemented, though, so this conflict resolution issue never really 
> comes up.
> If you want to re-use the existing implementation of the class method, 
> you can grab a reference to it before your category is created.  Any 
> more "conflict resolution" than that is probably a bad idea.

You've convinced me.. There really isn't a need to mark up the methods..

> This implementation allows you to extend any class that has a writable 
> dict, which is essentially "all" of them.  You can't extend built-in 
> types like str or object, though, unlike other languages with this 
> kind of facility.. but that is just not something you can do with the 
> Python runtime without hacking C structs (we did this in Stackless, 
> though, so it is possible but not recommended).
> What else would you want?  Why does the class have to know or care?  I 
> think this is one of those "consenting adults" things :)

For the same reason that classes declare what interfaces they provide, 
I guess.  The specific application I'm thinking of would have end-users 
defining category methods, so I prefer to be explicit about the 
'channels' (still can't think of a name) classes can be configured on.

/arg




More information about the PEAK mailing list