Adding method to class at run-time: bad style?

Grant Edwards invalid at invalid
Wed Apr 8 16:02:25 CEST 2009


On 2009-04-08, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote:

>>>      class Mixin:  # or class Mixin(object) if new-style:
>>>          def __eq__(self, other):
>>>              return (self.type == other.type ...
>>>          def __ne__(self, other):
>>>              return not self.__eq__(other)
>>>      class FancyControl(MixIn, ClientForm.Control): pass
>>>      class FancyCheckboxControl(MixIn, ClientForm.CheckboxControl): pass
>>>      ..
>>>      ClientForm.Control = FancyControl
>>>      ClientForm.CheckboxControl = FancyCheckboxControl
>>
>> That would work -- but there are probably 8 or 10 different
>> Control subclasses. It's a bit tedious mixing them all one at a
>> time, and you need more "inside" information (the names of all
>> the different subclasses).
>
> New style classes have a __subclasses__() method that could be used to  
> find all of them (*at a certain moment*) -- but considering all the  
> issues, I think that monkey-patching the base class is the "less bad"  
> option in this case...

I agree.  Inserting methods into the base class seems to be
working fine, and it's the least messy of the alternatives. I'd
submit a patch for ClientForm, but I don't know if my
definition of "equal" for a form/control is generally useful
enough to warrant being added to the package.

FWIW, I'm using it for automated regression-testing on a
product containing a web server.  Basically, I perform an
operation on the product, and then check to make sure that only
certain web pages/form/controls changed in the manner they
should have.

-- 
Grant Edwards                   grante             Yow! ... the HIGHWAY is
                                  at               made out of LIME JELLO and
                               visi.com            my HONDA is a barbequeued
                                                   OYSTER!  Yum!



More information about the Python-list mailing list