Locating source for any Python module

When I'm too lazy to find API documentation I just read the source code. To make this slightly easier in Python, here's what I use in my ~/.${SHELL}rc:

cdp () {
  cd "$(python -c "import os.path as _, ${1}; \
    print _.dirname(_.realpath(${1}.__file__[:-1]))"

For packages, this takes you to the corresponding source directory:

$ cdp twisted.web
$ pwd
$ ls
_auth/  domhelpers.py  html.py  iweb.py  resource.py

The realpath and [:-1] hackery follow any python-support symlinks. For "standalone" .py (or .so) modules, cdp will take you to the directory it resides in:

$ cdp subprocess
$ pwd
$ ls subprocess.py

Comments (5)

This is a really sweet command, very very nice!

April 23, 2010, 4:13 p.m. #
Jose Arthur Benetasso Villanova

Why not use ipython?

import subprocess

April 24, 2010, 3:28 a.m. #
That doesn't work so well for packages (try with "email") and I would prefer to use grep than search inside a pager. Also, more typing.

I'd use imp.find_module to find the location over explicitly importing it, but that's just personal preference.

April 25, 2010, 6:22 p.m. #

So cool and so useful. Many thanks for the knowledge, many, many thanks.

April 27, 2010, 8:45 a.m. #

Quite a few Django modules fail on import, here is a version that uses imp instead of import

cdp () {
cd "$(python -c "import sys, imp, os
path = sys.path
for i in '${1}'.split('.'): path = [imp.find_module(i,path)[1],]
path = path[0] if os.path.isdir(path[0]) else os.path.dirname(path[0])
print path")"

June 14, 2010, 6:08 a.m. #