Detect Unused Modules

K

Kamilche

'''
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()
 
S

Sybren Stuvel

Kamilche enlightened us with:
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.

Nice as it is, but why not use pylint to check this and many other
coding style issues?

Sybren
 
K

Kamilche

Nice as it is, but why not use pylint to check this and many other
coding style issues?

I made this the first time I mangled some code because pychecker said
some modules were not used when they really were. The module wasn't
that complex, only 302 lines, but it got it wrong.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,961
Messages
2,570,131
Members
46,689
Latest member
liammiller

Latest Threads

Top