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.)?
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.
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.
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.
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/.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With