[PYTHON] Find unused classes / methods / functions / variables in vulture

Update information has been posted on the TL of pypi_update, so I tried using it.

vulture

vulture points out unused classes / methods / functions / variables. https://pypi.python.org/pypi/vulture

Installation

You can install it with pip.

$ pip install vulture

Run

Once the installation is complete, you can use the vulture command. Run it using that command.

All objects are in use

I made a sample code that uses all the defined objects.

py


# -*- coding: utf-8 -*-
USE = 'use'


class Use(object):
    use_attr = 'use'

    def use(self, value):
        self.use_attr = value
        return self.use_attr


def use():
    Use.use(USE)

if __name__ == '__main__':
    use()

Run vulture on this sample code.

$ vulture use.py
$ echo $?
0

It ended without any indication.

All objects are unused

This time, on the contrary, I made a sample code in which all objects are not used.

py


# -*- coding: utf-8 -*-
UNUSE = 'unuse'


class UnUse(object):
    unuse_attr = 'unuse'

    def unuse(self, value):
        data = None


def unuse_func():
    func_data = None

Run vulture on this sample code.

$ vulture unuse.py
unuse.py:2: Unused variable 'UNUSE'
unuse.py:5: Unused class 'UnUse'
unuse.py:6: Unused variable 'unuse_attr'
unuse.py:8: Unused function 'unuse'
unuse.py:9: Unused variable 'data'
unuse.py:12: Unused function 'unuse_func'
unuse.py:13: Unused variable 'func_data'
$ echo $?
1


Seven cases were pointed out and it ended abnormally. Pointed out for global variables (UNUSE), classes (UnUse), class variables (unuse_attr), instance methods (UnUse.unuse), functions (unuse_func), and local variables (data and func_data). It is not pointed out whether the argument of the function or method is unused.

Setting-only member variables are pointed out

In the example below, the value is set to self.data, which is not completely unused. I just didn't get that value.

py


# -*- coding: utf-8 -*-


class Use(object):
    def __init__(self):
        self.data = 1

    def set_(self, value):
        self.data = value

Use()
Use.set_(2)

What happens if I run vulture on this sample code?

$ vulture unuse2.py
unuse2.py:6: Unused attribute 'data'
$ echo $?
1

I was pointed out where self.data = 1 in the constructor. It will be pointed out if you just set the value.

Recommended Posts

Find unused classes / methods / functions / variables in vulture
Using global variables in python functions
Dynamically define functions (methods) in Python
[Python3] Dynamically define global variables in functions
Practice applying functions and global variables in Python
A note on handling variables in Python recursive functions