Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get the file path of a class, function or Python module as pydoc and open it into your editor
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Damien Garaud
# Date: 2014
# License: Simplified BSD
"""Open a Python module in you editor when you're looking for a class, function
or module name.
# For a module
> ./ os.path
# For a function
> ./ numpy.ones
# For a class
> ./ pandas.DataFrame
Note: must be executable.
Put this in your PATH, rename it or create an alias.
from __future__ import print_function
import sys
import subprocess
import inspect
import pydoc
EDITOR = 'emacsclient'
OPTIONS = '-n'
def _getmodule_filepath(module):
return inspect.getabsfile(module)
def _try_get_module_path(name):
instance, name = pydoc.resolve(name)
if inspect.ismodule(instance):
return _getmodule_filepath(instance)
if len(sys.argv) != 2:
print("Take one argument: [module/class/func] NAME")
module_name = sys.argv[1]
instance, name = pydoc.resolve(module_name)
if inspect.ismodule(instance):
fpath = _getmodule_filepath(instance)
elif inspect.isbuiltin(instance):
fpath = _getmodule_filepath(inspect.getmodule(instance))
else: # function or class
fpath = _try_get_module_path(instance.__module__)
print("Open '{}' with {}".format(fpath, EDITOR))[EDITOR, OPTIONS, fpath])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment