Is there a reason not to do this?

Michele Simionato michele.simionato at gmail.com
Fri Dec 1 04:06:18 EST 2006


Ron Garret wrote:
> One of the things I find annoying about Python is that when you make a
> change to a method definition that change is not reflected in existing
> instances of a class (because you're really defining a new class when
> you reload a class definition, not actually redefining it).  So I came
> up with this programming style:
>
> def defmethod(cls):
>   return lambda (func): type.__setattr__(cls, func.func_name, func)

Why not just ``return lambda func: setattr(cls, func.func_name, func)``
?
Your approach is certainly uncommon, but for your use case it seems to
me
a pretty much decent solution. The only thing I don't like is that all
your
functions/methods will end up begin 'None'. I'd rather to be able to
use
the help, so I would write

def defmethod(cls):
    def decorator(func):
        setattr(cls, func.func_name, func)
        return func
    return decorator

@defmethod(C)
def m1(self, x):pass

help(m1)


BTW, for people with a Lisp background I recommend using IPython with
emacs  and the
ipython.el mode. It is pretty good, even if not comparable to Slime.

                                     Michele Simionato




More information about the Python-list mailing list