Detect Unused Modules

Kamilche klachemin at comcast.net
Fri Oct 20 19:08:27 EDT 2006


'''
DetectUnusedModules.py - Detect modules that were imported but not used
in a file.
When run directly, this class will check all files in the current
directory.
'''

import os
import tokenize

class PrintUnusedModules(object):
    state = 0
    importlist = None
    linenumbers = None

    def __init__(self, filename):
        self.filename = filename
        self.importlist = {}
        self.linenumbers = {}
        fd = open(filename, 'rU')
        tokenize.tokenize(fd.readline, self.FindImports)
        fd = open(filename, 'rU')
        tokenize.tokenize(fd.readline, self.FindReferences)
        for mod, ctr in self.importlist.items():
            if ctr == 0:
                print '   File "%s", line %d, "%s" is imported but not
referenced.' % (self.filename, self.linenumbers[mod], mod)

    def FindImports(self, toktype, tokval, tokstart, tokend, tokline):
        ' Build a list of modules this module imports'
        if self.state == 0:
            if toktype == tokenize.NAME:
                if tokval == 'import':
                    self.state = 1
                    self.mods = []
        elif self.state == 1:
            if toktype == tokenize.NAME:
                if tokval == 'import':
                    pass
                elif tokval == 'as':
                    del self.mods[-1]
                else:
                    self.mods.append((tokval, tokstart[0]))
            elif toktype == tokenize.OP:
                pass
            elif toktype == tokenize.NEWLINE:
                for mod, linenum in self.mods:
                    self.importlist[mod] = 0
                    self.linenumbers[mod] = linenum
                self.state = 0

    def FindReferences(self, toktype, tokval, tokstart, tokend,
tokline):
        ' Find all references to the imported modules'
        if self.state == 0:
            if toktype == tokenize.NAME:
                if tokval == 'import':
                    self.state = 1
                elif tokval in self.importlist:
                    self.importlist[tokval] += 1
        elif self.state == 1:
            if toktype == tokenize.NEWLINE:
                self.state = 0

def ProcessDir(pathname = None):
    if pathname == None:
        pathname = os.getcwd()
    else:
        pathname = os.path.abspath(pathname)
    for shortname in os.listdir(pathname):
        filename = os.path.join(pathname, shortname)
        if filename[-3:] == '.py':
            print 'Checking %s...' % filename
            PrintUnusedModules(filename)

def main():
    print 'Unused Module List'
    ProcessDir()
    print 'Done!'

if __name__ == '__main__':
    main()




More information about the Python-list mailing list