Wandering Thoughts archives

2005-12-15

Another introspection trick

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.)

AnotherIntrospectionTrick written at 14:32:52; Add Comment


Page tools: See As Normal.
Search:
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.