List all functions defined in a python program

Gribouillis 2 Tallied Votes 204 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

# printdef.py
# prints the names of all function definitions found in a program
# usage: python printdef.py myprogram.py

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 = tokens.next()
      if func[0] == NAME:
        yield func[1]


if __name__ == "__main__":
  import sys
  programPath = sys.argv[-1]
  if programPath[-3:] != ".py":
    print "usage: printdefs.py <path to '.py' file>"
    sys.exit(-1)
  for name in getDefSequence(programPath):
    print name
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.