Is there a reason not to do this?

Diez B. Roggisch deets at nospam.web.de
Thu Nov 30 18:14:22 EST 2006


Ron Garret schrieb:
> 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)
> 
> class c1(object): pass
> 
> @defmethod(c1)
> def m1(self, x): ...
> 
> 
> Now if you redefine m1, existing instances of c1 will see the change.
> 
> My question is: is there a reason not to do this?  Does it screw 
> something up behind the scenes?  Is it unpythonic?  Why isn't this 
> standard operating procedure?

What are you doing that needs this permanent redefinition? I like the 
repl, yet usually - especially when dealing with classes - I write a 
text file containing code. So, i just run that on a command line again, 
if I made some changes, recreating whatever objects I want again.

Even if I'd not do that, but used a long-running interpreter inside an 
IDE (which is what I presume you are doing) - why do you _care_ about 
the old objects the first place? I mean, you obviously changed the 
classes for a reason. So, you are not being productive here, but still 
programming. Which means that you don't _have_ to care about old, 
unchanged objects too much.

But in the end - it's your code. It will run slower, it looks kinda 
weird as someone who's reading it has to know what it is for, but if it 
suits your needs - do it.

Diez



More information about the Python-list mailing list