How can you find unused functions in Python code?

So, you have some old code lying in a pretty healthy project. How can you find and remove dead functions?

I saw these two links: Find unused code and Tool for finding unused functions in a php project , but they seem specific to C # and PHP, respectively.

Is there a Python tool to help you find functions that are not mentioned anywhere in the source code (despite reflection / etc)?

+41
python refactoring dead-code
Mar 28 '09 at 16:42
source share
5 answers

In python, you can find unused code using dynamic or static code analyzers. Two examples for dynamic analyzers are coverage and figleaf . They have the disadvantage that you have to run all possible branches of your code to find the unused parts, but they also have the advantage that you get very reliable results.

Alternatively, you can use static code analyzers that just look at your code but don't actually run it. They work much faster, but due to the dynamic nature of python, the results are not 100% accurate, so you can double check them. The two tools that come to mind are pyflakes and vulture . They complement each other: Pyflakes finds unused imports and unused local variables, while the vulture finds unused functions, methods, classes, variables and attributes.

Tools are available in the Python package index http://pypi.python.org/pypi .

+36
Mar 22 2018-12-22T00:
source share

pylint can do what you want.

+13
Mar 28 '09 at 17:39
source share

I'm not sure if this is useful, but you can try using coverage , figleaf, or other similar modules that record what parts of your source code are used when running your scripts / applications.

+4
Mar 28 '09 at 19:21
source share

Due to the rather tough way of representing python code, would it be difficult to create a list of functions based on a regular expression looking for def function_name(..) ?

And then look for each name and sum how many times it shows in the code. Naturally, this would not take comments into account, but so far you are looking at functions with less than two or three instances ...

This is a bit Spartan, but it sounds like a good weekend sleep task =)

+1
Mar 28 '09 at 17:11
source share

if you don’t know that your code uses reflection, as you said, I would go for the trivial grep. Do not underestimate the power of an asterisk in vim (it searches for the word that you have under the cursor in the file), although this is limited only to the file that you are currently editing.

Another solution that you could implement is to have a very good testuite (rarely, unfortunately), and then complete the procedure using the deprecation procedure. if you get obsolete output, it means the procedure was called, so it is still in use somewhere. This works even for reflection behavior, but, of course, you can never be sure that you are not fulfilling the situation when your regular call is made.

+1
Mar 28 '09 at 19:44
source share



All Articles