On 9-Sep-05, at 10:54 AM, Kirby Urner wrote:
Yeah, this is clever, I like it. You slam the door from the inside,interpose a "door closed" next time run() is called -- likely in error.
It's usful for things where a decision needs to be made *once* rather than testing a condition every time the code is run, so instead of:
class MyUsualThing(object):
def doYourThing(self, x,y,z):
if isThisAMac():
# mac code here
elif isThisWindows():
# windows code here
elif isThisLinux():
# linux code here
you can do:
class MyTrampolinedThing(object):
def _doMacThing(self, x,y,z):
# mac code here
def _doWindowThing(self, x,y,z):
# windows code here
def _doLinuxThing(self, x,y,z):
# linux code here
def doYourThing(self, x,y,z):
klas = self.__class__
if isThisAMac():
klas.doYourThing = klas._doMacThing
elif isThisWindows():
klas.doYourThing = klas._doWindowsThing
elif isThisLinux():
klas.doYourThing = klas._doLinuxThing
del klas._doMacThing
del klas._doWindowsThing
del klas._doLinuxThing
return self.doYourThing(x,y,z)
You could of course define your specific handlers inline in the
doYourThing method before it is replaced, but I think it's clearer to
define them seperately and then delete them to clean up the object
namespace. As you can see, this could be confusing if you get a
stacktrace which lists doYourThing, because this method will only
ever be called once, and after that the doYourThing will be one of
the other methods. Still, it avoids a test on subsequent calls and
possibly a function call or two.
Just remember that premature optimization is the root of all evil. If trampolining make the code flow *more* readable, use it. Or, if your code is too slow, and you've profiled it and found that the tests are the culprit, then use it. Otherwise, it can make your objects into a jumbled, untraceable mess.
--Dethe "All spiritual paths have four steps: show up, pay attention, tell the truth, and don't be attached to the results." Angeles Arien
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________ Edu-sig mailing list [email protected] http://mail.python.org/mailman/listinfo/edu-sig
