473,769 Members | 5,823 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is there a reason not to do this?


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?

rg
Nov 30 '06 #1
16 1201
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
Nov 30 '06 #2
In article <4t************ *@mid.uni-berlin.de>,
"Diez B. Roggisch" <de***@nospam.w eb.dewrote:
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
Dec 1 '06 #3
Ron Garret wrote:
In article <4t************ *@mid.uni-berlin.de>,
"Diez B. Roggisch" <de***@nospam.w eb.dewrote:
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?
1. Do you mean, is there an "it'll crash the interpreter" reason? No.
2. Not for most ordinary cases. There are a few gotchas (for example,
use of __private variables), but they're minor.
3. Yes.
4. Because it's unPythonic.

But don't worry too much if you do something unPythonic occasionally.
Python says there's should be one--and preferably only one--obvious way
to do it. So if there's no obvious way to do it, you probably have to
do something unPythonic. (Or consult someone with more experience. :)
[snip]
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.
Seems like a reasonable use case to me.
If there's a better way to accomplish all this I'm all ears.
A straightforward , Pythonic way to do it would be to create an
intermediate representation that understands both the existing class
interfaces and the RDB stuff, but that could lead to synchronizing
problems and a big hit in performance. And it's probably a lot of work
compared to tacking on methods. OTOH, it could help with hairiness you
mention. (I recently did something similar in one of my projects,
though the intermediary was transient.)

You might be able to create a set of augmented subclasses to use
instead. The main problem with this is that base classes often don't
know about the augmented versions. You'd have to override code that
requires an ordinary object with code that allows an augmented object.
This is sometimes very inconvenient (like when the code requiring an
ordinary object is one line smack in the middle of a 100-line
function).

It actually sounds like Aspect Oriented Programming might be helpful
here (if you care to learn another wholly different programming
paradigm, that is). You have a concern (persistence) that's pretty
much off in another dimension from the purpose of the classes.
Or maybe the best way is just to teach an old class new tricks.
Carl Banks

Dec 1 '06 #4
"Carl Banks" <pa************ @gmail.comwrote in message
news:11******** **************@ f1g2000cwa.goog legroups.com...
>
A straightforward , Pythonic way to do it would be to create an
intermediate representation that understands both the existing class
interfaces and the RDB stuff, but that could lead to synchronizing
problems and a big hit in performance. And it's probably a lot of work
compared to tacking on methods. OTOH, it could help with hairiness you
mention. (I recently did something similar in one of my projects,
though the intermediary was transient.)
I would second Carl's recommendation that you find some way to persist an
interim version of these expensive-to-create objects, so you can quickly
load debuggable instances to accelerate your development process. With
luck, you can get by with out-of-the-box marshal/unmarshal using the pickle
module. We've done this several times in my office with objects that an
application creates only after some extensive GUI interaction - it just
slows down development too much without some quick import of debuggable
instances.

Even though this seems like a sidetrack, it's a pretty direct shortcut,
without too much unusual technology or design work.

-- Paul
Dec 1 '06 #5
"Ron Garret" <rN*******@flow net.comwrote:

>
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:
I would have thought that not changing yesterday was the very essence of
dynamism (dynamicness ??) - but that when you change something - it applies from
that point in time forwards...

What do you propose to do about the outputs from such classes that have already
happened?

confused - Hendrik

Dec 1 '06 #6
In article <ma************ *************** ***********@pyt hon.org>,
"Hendrik van Rooyen" <ma**@microcorp .co.zawrote:
"Ron Garret" <rN*******@flow net.comwrote:


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:

I would have thought that not changing yesterday was the very essence of
dynamism (dynamicness ??) - but that when you change something - it applies
from that point in time forwards...
I don't want to get into a philosophical debate. I'll just point you to
CLOS as an example of an object system that already works this way.
What do you propose to do about the outputs from such classes that have
already happened?
The ability to change methods on the fly will be used mainly for
debugging I expect.

rg
Dec 1 '06 #7
In article <rN************ *************** **@news.gha.cha rtermi.net>,
Ron Garret <rN*******@flow net.comwrote:
In article <ma************ *************** ***********@pyt hon.org>,
"Hendrik van Rooyen" <ma**@microcorp .co.zawrote:
"Ron Garret" <rN*******@flow net.comwrote:

>
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:
I would have thought that not changing yesterday was the very essence of
dynamism (dynamicness ??) - but that when you change something - it applies
from that point in time forwards...

I don't want to get into a philosophical debate.
Actually, I changed my mind. Consider:

def g(): print 'G'

def h(): print 'H'

def f(): g()

class C1:
def m1(self): f()

class C2:
def m1(self): g()

c1 = C1()
c2 = C2()

def f(): h()

class C2:
def m1(self): h()

c1.m1() # Prints H
c2.m1() # Prints G

On what principled basis can you justify two different outputs in this
case? Why should I be able to change the definition of f and not have
to go back and recompile all references to it, but not m1?

rg
Dec 1 '06 #8
In article <z3************ *****@tornado.t exas.rr.com>,
"Paul McGuire" <pt***@austin.r r._bogus_.comwr ote:
"Carl Banks" <pa************ @gmail.comwrote in message
news:11******** **************@ f1g2000cwa.goog legroups.com...

A straightforward , Pythonic way to do it would be to create an
intermediate representation that understands both the existing class
interfaces and the RDB stuff, but that could lead to synchronizing
problems and a big hit in performance. And it's probably a lot of work
compared to tacking on methods. OTOH, it could help with hairiness you
mention. (I recently did something similar in one of my projects,
though the intermediary was transient.)
I would second Carl's recommendation that you find some way to persist an
interim version of these expensive-to-create objects, so you can quickly
load debuggable instances to accelerate your development process. With
luck, you can get by with out-of-the-box marshal/unmarshal using the pickle
module. We've done this several times in my office with objects that an
application creates only after some extensive GUI interaction - it just
slows down development too much without some quick import of debuggable
instances.

Even though this seems like a sidetrack, it's a pretty direct shortcut,
without too much unusual technology or design work.
These objects can be parts of huge networks of massively linked data
structures. They are in constant flux. It is not uncommon to hit a bug
after many minutes, sometimes hours, of computation. Having to store
the whole shlemobble after every operation would slow things down by
orders of magnitude. And writing code to be clever and only store the
dirty bits would be a pain in the ass. I think I'll stick with Plan A.

rg
Dec 1 '06 #9
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

Dec 1 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3121
by: Alexandros Frantzis | last post by:
Hello! Is there a standard way to find the reason a file stream open failed (eg file doesn't exist, access rights)? Thanks.
10
36646
by: Jag | last post by:
can anyone tell me what is SQL0911 reason code 68 thanks jag
1
6011
by: Stefano Tesini | last post by:
Hi all, when i drop a table, i take his error : SQL0902C System error (REASON CODE = "122"). Why ? Ver UDB Server nt 7.1.0 Ver UDB Cli 7.1.0 Win 98 or XP the error is the same.
3
5682
by: Eveline | last post by:
Dear all, I have a database on which I do stuff like: - creating tables - filling those tables with data - joining tables - EXPORT of queries to file - LOAD data from file into a tables
4
5838
by: acemann7 | last post by:
Windows 2000 udb v 7.2 Got the latest fixpak 13 Applied it. Still can't get a single java sp to run. I used to get reason "2"... now reason "0" - reason 0 is not even documented. I point jdk11_path to: Java Development Kit 1.1 installation path (JDK11_PATH) =
1
2701
by: Ted | last post by:
Hello, Is there an equivalent to die(reason) in ASP.NET? I have a ValidateData() function that returns a boolean, so instead of If condition Then Response.Writeline(reason): Return False I want
9
6709
by: shorti | last post by:
db2 V8.2 I have been looking for a good way to log the 'reason code' when we hit an sqlcode that uses them. From what I can tell the reason code is stored in sqlca.sqlerrmc. But, there seems to be other information stored in this string besides the reason code. The DB2 Info Center website states that sqlca.sqlerrml identifies whether sqlerrmc contains valid data and the length of the data so I added code that would copy the content...
8
23476
by: Challenge | last post by:
Hi, I got error, SQL1768N Unable to start HADR. Reason code = "7", when I tried to start hadr primary database. Here are the hadr configuration of my primary db: HADR database role = STANDARD HADR local host name (HADR_LOCAL_HOST) = testserver HADR local service name (HADR_LOCAL_SVC) = 56000 HADR remote host name (HADR_REMOTE_HOST) = testserver
2
2579
by: BD | last post by:
Hi, all. I'm trying to implement a REFRESH IMMEDIATE MQT to help with performance of a particularly sluggish query. I cannot create it with REFRESH IMMEDIATE, because of reason code "10", whatever that is. I am able to implement it with REFRESH DEFERRED, but that's not really suitable. I need to get a handle on these reason codes.
16
1765
by: John Salerno | last post by:
Just something that crosses my mind every time I delve into "Learning Python" each night. Does anyone see any value in learning Python when you don't need to for school, work, or any other reason? I mean, sure, there's value in learning anything at any time, but for something like a programming language, I can't help but feel that I will be mostly unable to use what I learn simply because I have no reason to use it. The *process* of...
0
9586
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10043
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8869
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3956
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.