Wrp Yuexia
Wrp Yuexia

Reputation: 103

How do I find and remove unused functions in Python code files?

I have a Python code file with many functions in it. I'm only using a few. Is there a tool available to remove all of the unused ones for me?

Upvotes: -1

Views: 2924

Answers (1)

MarredCheese
MarredCheese

Reputation: 20791

As Steve mentioned in the comments, you could use Vulture.

Here's an example from the documentation

Consider the following Python script (dead_code.py):

import os

class Greeter:
    def greet(self):
        print("Hi")

def hello_world():
    message = "Hello, world!"
    greeter = Greeter()
    greet_func = getattr(greeter, "greet")
    greet_func()

if __name__ == "__main__":
    hello_world()

Calling

vulture dead_code.py

results in the following output:

dead_code.py:1: unused import 'os' (90% confidence)
dead_code.py:4: unused function 'greet' (60% confidence)
dead_code.py:8: unused variable 'message' (60% confidence)

Upvotes: 4

Related Questions