Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you find unused functions in Python code?

So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?

I've seen these two references: Find unused code and Tool to find unused functions in php project, but they seem specific to C# and PHP, respectively.

Is there a Python tool that'll help you find functions that aren't referenced anywhere else in the source code (notwithstanding reflection/etc.)?

like image 885
Brian M. Hunt Avatar asked Mar 28 '09 16:03

Brian M. Hunt


People also ask

What is a dead code in Python?

When a function reaches a return statement, it immediately ends execution of that function and returns a value to the calling environment. 00:15 Any code that follows that return statement is often referred to as dead code. The Python interpreter completely ignores this dead code when executing your functions.

How do you remove unused variables in Python?

First, the syntax tree of the source is traversed and all unused target assignment statements are discovered. Second, the tree is traversed again via a custom ast. NodeTransformer class, which removes these offending assignment statements. The process is repeated until all unused assignment statements are removed.

What is vulture in Python?

Vulture finds unused code in Python programs. This is useful for cleaning up and finding errors in large code bases. If you run Vulture on both your library and test suite you can find untested code. Due to Python's dynamic nature, static code analyzers like Vulture are likely to miss some dead code.


2 Answers

In Python you can find unused code by using dynamic or static code analyzers. Two examples for dynamic analyzers are coverage and figleaf. They have the drawback that you have to run all possible branches of your code in order to find 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 run much faster, but due to Python's dynamic nature the results may contain false positives. Two tools in this category are pyflakes and vulture. Pyflakes finds unused imports and unused local variables. Vulture finds all kinds of unused and unreachable code. (Full disclosure: I'm the maintainer of Vulture.)

The tools are available in the Python Package Index https://pypi.org/.

like image 55
Jendrik Avatar answered Sep 23 '22 02:09

Jendrik


I'm not sure if this is helpful, but you might try using the coverage, figleaf or other similar modules, which record which parts of your source code is used as you actually run your scripts/application.

like image 21
Noah Avatar answered Sep 20 '22 02:09

Noah