Python Forum
Finding dead code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Finding dead code (/thread-1279.html)



Finding dead code - Ofnuts - Dec-20-2016

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 :)


RE: Finding dead code - Larz60+ - Dec-20-2016

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/download.html#gitrepos

Typical output:
[Image: regexp_ungrouped.png]


RE: Finding dead code - wavic - Dec-20-2016

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'



RE: Finding dead code - micseydel - Dec-20-2016

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.


RE: Finding dead code - Ofnuts - Dec-20-2016

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.


RE: Finding dead code - Larz60+ - Dec-20-2016

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


RE: Finding dead code - wavic - Dec-20-2016

Yes. It's called pylint if I remember. I didn't get it at allĀ  Big Grin