1

Background

  • I'm creating a Most Recently Used Function Browser plugin for Vim.
  • I need to find the name of the current function the cursor is in.
  • For other languages I could search for "{ }" enclosures, but python uses whitespace/tabs.

Example

Assume I have these functions in foo.py...

def foo(file):
    fileLines = []
    with open(file, 'r') as f:
        for line in f:
            fileLines.append(line)

    def nested_function():
        pass

    # FILE POSITION
    for line in fileLines:
        print line

I want to write a function that returns the name of the function of a position ("FILE POSITION" in the example)

def get_function_scope(sourceFile, lineNumber, columnNumber):
    pass

So for the above example I want something like...

fxnName = get_function_scope("foo.py", lineNumber=9, columnNumber=4)
print fxnName
# "foo"

Approaches

  • Exuberant CTags gives me a nice list of all function/class/method locations but not the line numbers of the scope each function occupies.
  • Not sure if inspect can help even if code isn't "live"?
  • I'm thinking of working backwards from the indents until I reach a function/method definition.

Is there is a standard way of doing this that I'm not aware of?

4

1 回答 1

0

这是我想出的解决方案:

https://gist.github.com/cgreer/7366297

于 2013-11-08T04:35:23.197 回答