Is there a reason not to do this?

Ron Garret rNOSPAMon at flownet.com
Thu Nov 30 20:00:38 EST 2006


In article <4t96ujF134nv7U1 at mid.uni-berlin.de>,
 "Diez B. Roggisch" <deets at nospam.web.de> wrote:

> 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

I have two motivations.

First, I'm dealing with some classes whose instances take a long time to 
construct, which makes for a long debug cycle if I have to reconstruct 
them after every code change.

Second, the design just naturally seems to break down that way.  I have 
a library that adds functionality (persistence) to a set of existing 
classes.  The persistence code stores the objects in a relational DB, so 
it's pretty hairy code, and it has nothing to do with the functionality 
that the classes actually provide.  The original classes are useful even 
with the persistence code, and I'm trying to keep things lightweight.

If there's a better way to accomplish all this I'm all ears.

rg



More information about the Python-list mailing list