Another introspection trick

December 15, 2005

Here's another example of Python's introspection and command interpreter being useful:

[x for x in dir(m) if isinstance(getattr(m, x), str) and 'localhost' in getattr(m, x)]

One of our Mailman lists had been accidentally set up thinking that the machine's name was 'localhost', instead of the machine's actual hostname, and this was causing problems. Mailman is written in Python and offers access to the internals of list data via an interactive Python interpreter (through the withlist program). This one-off bit of introspection was basically a grep over all the lists's attributes.

I won't claim that this would be good style in a program, but as something I typed at the Python interpreter's command line it was very handy. In this, it's like shells and shell scripts; we do things on the command line that we'd never do in shell scripts.

(The isinstance() check is necessary to keep the next clause from potentially throwing an exception on non-string attributes, which would abort the entire list comprehension.)

Written on 15 December 2005.
« Reddit versus Digg: a little detail that matters
On the name of USB flash memory drives »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Thu Dec 15 14:32:52 2005
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.