Using Python introspection for semi-evilNovember 9, 2005
One of the things I write in Python is network daemons. Because it works so nicely, network daemons usually take input as text lines that start with a command word and have whitespace separated arguments. There's a certain amount of eye-rolling tedium in writing code to check that the command word is valid and has the right number of arguments. When I wrote a program that does a lot of this, the tedium finally got to me and I sort of snapped and automated all of the validation through Python's introspection features. The program's basic structure has an object for each connection. Each command is handled by a method function on the object, and the functions all take normal argument lists. (So they are not passed the command line as a big list or anything.) The name of each command method is ' (This is a fairly common pattern in Python; see, for example, how
BaseHTTPServer
handles dispatching To check that the number of arguments was right, I reached into the handler function I'd just found and fished out how many arguments it expected to be called with (compensating for the additional 'self' argument that method functions get). This isn't at all general, but I didn't need generality; the network daemon's commands all have a fixed number of arguments. The code wound up looking like this:
(The real version used more elaborate error handling for 'empty line', 'no such command', and 'wrong number of arguments'.) Normally I would have to account for the extra (I did say this was semi-evil.) Comments on this page:
From 192.88.60.254 at 2005-11-09 14:41:31:
By cks at 2005-11-09 17:08:40:
|
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |