Python Forum

Full Version: Finding dead code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm writing a fairly large a script (currently around a thousand lines and growing(*)) and due to refactoring it could contain some dead code (I already found some...). Short of searching each function by hand, is there a tool somewhere to build the calling tree? I'm not using any IDE at the moment, just an editor (Kate).

(*) no, I can't split it in modules :)
See: http://pycallgraph.slowchop.com/en/master/
It might do what you want.
Also, there's Doxygen which is a document generator from source,
this mignt not do the trick if it follows the dead code here's the link: http://www.stack.nl/~dimitri/doxygen/dow...l#gitrepos

Typical output:
[Image: regexp_ungrouped.png]
Try https://pypi.python.org/pypi/vulture

There are some Python IDE's which will mark unused variables or code which is not used. Sublime Text will do it, I think. May be Atom too.

Edit:
I've wrote this simple code:

#!/usr/bin/env python3
import sys

a = 2
b = 3
c = 4


def print_hw():
    print("hello, world")


def add_nums(x, y):
    return x + y


def main():
    print(add_nums(a, b))
    print(dir(__name__))

if __name__ == '__main__':
    sys.exit(main())
So, Sublime, Atom and Ninja IDE, no one of these has showed the unused code...

I've tried pychecker, pyflakes and vulture. Only the last one has printed out some result.

victor@jerry:~$ vulture -v dead_code_test.py | grep 'Unused'
dead_code_test.py:6: Unused variable 'c'
dead_code_test.py:9: Unused function 'print_hw'
Great suggestions above, but you can also try using a code coverage tool - https://coverage.readthedocs.io/en/coverage-4.2/
From my Googling though, Vulture seems like the best way to go.
Vulture definitely fits the bill, even if it flagged wrongly an unused attribute (it assumes that the data is used only by my code...). Small price to pay for the rest... and it's fast.

Will look at larz60+'s graph tools later, when I get utterly lost(*) :)

(*) The script is a rat's nest of closures being called by dynamically selected functions.
Is there a python lint?

I just searched and found pylint https://github.com/PyCQA/pylint
Don't know anything abut it
some lints don't do code coverage
Yes. It's called pylint if I remember. I didn't get it at allĀ  Big Grin