Create classes at runtnime

Peter Otten __peter__ at
Sat Feb 5 07:09:31 EST 2011

Carl Banks wrote:

> On Feb 4, 1:32 pm, Peter Otten <__pete... at> wrote:
>> Marc Aymerich wrote:
>> > I need to create a pretty complex class at runtime. something like
>> > this one:
>> I have a hunch that you've never heard the famous Kernighan quote:
>> "Everyone knows that debugging is twice as hard as writing a program in
>> the first place. So if you're as clever as you can be when you write it,
>> how will you ever debug it?"
>> Or that if you've heard it you don't heed it.
> [snip]
>> > What is your recommendation?
>> Find something that is simple and robust. Something else.
> I've done things like this before, and I would say the Kernigan quote
> is not appropriate here, and the implication that isn't not simple and
> robust is incorrect.  It's repetitive code like the OP posted that's
> complex and flimsy.  Repetitive code is the exact opposite of the DRY
> principle, and there's a reason DRY is one of the most often cited
> principles here.
> Using advanced techniques like metaclasses to exploit the similarity
> to reduce or eliminate the repetitiveness can, if done well, simplify
> code.  By a lot.
> Advanced is not the same thing as complex.
> In this particular case I'd say the recommendation to do something
> else is a good one, but it's not true in general.

The trouble with metaclasses is that they are not completely transparent.
Instead of two levels (class and instance) you have to consider three. 
Steven D'Aprano has involuntarily given an example of what may go wrong.

Marc has asked another question with a problem that could be attacked with a 
metaclass before. Had he been comfortable with metaclasses by now we 
wouldn't have seen the above post. So he is operating at the limits of his 
current understanding of Python in an area where it is not unlikely that 
he'll run into unexpected side effects of the django database wrapper. 

I think a reminder that he has to debug the whole thing is in order ;)


More information about the Python-list mailing list