MOPs (warning: LONG)

Ian Bicking ianb at colorstudy.com
Fri Oct 24 01:00:59 EDT 2003


On Thursday, October 23, 2003, at 08:30 PM, Joachim Durchholz wrote:
> What is dynamic metaprogramming good for?
[...]
> - Dynamic fields
> Frankly, I don't understand why on earth one would want to have 
> objects with a variant set of fields. I could do the same easily by 
> adding a dictionary to the objects, and be done with it (and get the 
> additional benefit that the dictionary entries will never collide with 
> a field name).
> Conflating the name spaces of field names and dictionary keys might 
> offer some syntactic advantages (callers don't need to differentiate 
> between static and dynamic fields), but I fail to imagine any good use 
> for this all... (which may, of course, be lack of imagination on my 
> side, so I'd be happy to see anybody explain a scenario that needs 
> exactly this - and then I'll try to see how this can be done without 
> MOP *g*).

I happily do just this in SQLObject.  Subclasses define columns, but 
columns are fairly complicated and can entail secondary methods, in 
addition to the getter/setter methods.  More complex might be a class 
built from a XML schema, which again has a clearly defined set of 
attributes, but those attributes vary.

Both instances could be done with dictionary access, but frankly that's 
just dumb -- they aren't dictionaries.  Maybe it's okay for a 
generalized XML object, but if you are building off a schema it's more 
appropriate to use the restricted namespace that classes attributes 
generally imply.  Both cases could be done with __getattr__, but that's 
kind of wasteful as well -- why are you trapping every attribute that 
isn't found, when you know at the time of class creation time exactly 
what attributes you want?

In both cases, however, you can "build" the class -- i.e., create the 
class, then add class variables to do whatever you need to do.  This 
doesn't look as nice, but it's really the same sort of thing.  Many 
kinds of metaclasses wouldn't be necessary is there was something like 
a __cls_init__ method, called on class instantiation.


Hmmm... in another case I use a __call__ in a metaclass so that calling 
a class subclasses it instead of instantiating it.  Good fun, but a 
little obscure in purpose.

--
Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org






More information about the Python-list mailing list