[Python-Dev] Monkeypatching idioms -- elegant or ugly?

"Martin v. Löwis" martin at v.loewis.de
Sat Jan 19 19:53:42 CET 2008


> In Objective-C it's perfectly common to extend existing classes using  
> 'categories' and I have often found this idiom very useful.  What is  
> described here is basically categories for Python.  I've implemented  
> something like this before and I would be happy to see this added to  
> the standard library and formalised.

If they are like Smalltalk categories, then they are semantically
different. For method categories, you group the methods by
"functionality" or "purpose" or "intended audience", as the developer
of a class. It is important that the category has a name, and the
categories are part of the class' documentation.

For monkey-patching classes, the grouping is "by application". The
additional/changed methods are not written by the author of the
class, but by the author of the application using the class. The
name of the group is irrelevant, and the documentation (if any exists)
documents it as an application-specific thing.

In-between are the partial classes of C# and the way C classes
get implemented: it is the implementor of the class who fragments
the class into separate pieces of code, but not for the sake
of the class clients, but for maintainability of the class itself
(so that you can spread a large class over several source files).

They use same implementation strategy; for integrating it into the
standard library, I think the usage scenarios need to be considered
more. I like to see all three scenarios supported; to support categories
properly, you need to also have support in the reflection, in pydoc,
and perhaps also in the online documentation (if standard library
classes get split into categories).

Regards,
Martin


More information about the Python-Dev mailing list