Python's extra-clever help() function

September 11, 2006

I recently used 'help()' on one of my own internal modules, mostly as a quick way to browse the entire function/class collection in one go. Now, I'm kind of a slacker when it comes to using docstrings (for some reason I prefer comments before the function), so I didn't expect to see very much in the help() output.

Much to my surprise I saw things like:

  # Extract the host from the
  # REQUEST_URI, if it is present.

The amount of introspective magic required to do this turns out to be pretty impressive; for extra points, it's pretty much all done in Python.

The help() function is a shim created in as an instance of a class. The function wraps, which winds up calling on inspect.getcomments() for the heavy lifting. This works by finding and scanning the source file itself, starting from the co_filename and co_firstlineno attributes that the bytecode compiler glues on things.

(I should probably get over my reluctance to use docstrings, especially if I'm putting the exact same information in the comments. At the moment I like the visual look of comments better; docstrings make me feel that the documentation is quietly disappearing into the rest of the code.)

Written on 11 September 2006.
« 'In place' filesystem defragmentation with Disksuite
A quick note about how extended partitions work »

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

Last modified: Mon Sep 11 22:08:22 2006
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.