List all functions defined in a python program

Gribouillis 2 Tallied Votes 206 Views Share

This is a command line utility which lists the names of all functions defined in a python source file with a def <name> statement

#!/usr/bin/env python

# prints the names of all function definitions found in a program
# usage: python

from tokenize import generate_tokens, NAME

def getDefSequence(programPath):
  # generator of the names of all python fonctions defined in file programPath
  tokens = generate_tokens(open(programPath, "r").readline)
  for token in tokens:
    if token[0] == NAME and token[1] == "def":
      func =
      if func[0] == NAME:
        yield func[1]

if __name__ == "__main__":
  import sys
  programPath = sys.argv[-1]
  if programPath[-3:] != ".py":
    print "usage: <path to '.py' file>"
  for name in getDefSequence(programPath):
    print name