event handler advice
sblakey at freei.com.bbs
sblakey at freei.com.bbs
Mon Jul 17 20:20:02 EDT 2000
On Mon, Jul 17, 2000 at 03:49:02PM -0700, Pete Shinners wrote:
> i'm trying to write a simple event handler python class.
> so far i haven't come up with an 'elegant' solution i was
> expecting.
>
<<snipped by Sean Blakey>>
>
> my guess is i need some dictionary that defines the
> messages and their routine name (no shortcut way to do
> this unless python had #define like macros :])
>
> messages = {msg.INIT:"INIT", msg.PLAY:"PLAY", ...etc}
>
> then a routine like
>
> class basehandler:
> def handle(messageid):
> name = messages[messageid]
> self.name() #HAHA, no really, how do i do this?
>
> but i'm not exactly sure how to write this. need help, thx
>
>
>
Probably he simplest solution is along the lines of:
class basehandler:
def handle(messageid):
name = messages[messageid]
bound_method = getattr(self, name)
bound_method()
Personally, I would be more comfortable with:
class basehandler:
def handle(messageid):
try:
name = messages[messageid]
bound_method = getattr(self, name)
except KeyError:
if __debug__: print 'Invalid message sent', messageid
# or other error handling (syslog?)
except AttributeError:
if __debug__: print 'Unhandled message received', name
# other misc error handling
else:
bound_method()
This approach allows trapping of "illegitimate" messages (or messages you
haven't gotten around to implementing yet) without the nastiness of an unhandles
exception.
-Sean
--
Sean Blakey, sblakey at freei.com
Software Developer, FreeInternet.com
(253)796-6500x1025
"It ain't so much the things we don't know that get us in trouble. It's the
things we know that ain't so."
-- Artemus Ward aka Charles Farrar Brown
More information about the Python-list
mailing list