How can you find unused functions in Python code?

左心房为你撑大大i 提交于 2019-11-26 22:01:47
Jendrik

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 are not 100% accurate so you might want to double-check them. Two tools that come to mind are pyflakes and vulture. They are complementary: Pyflakes finds unused imports and unused local variables while vulture finds unused functions, methods, classes, variables and attributes.

The tools are available at the Python Package Index http://pypi.python.org/pypi.

Anonymous

pylint can do what you want.

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.

Because of the fairly strict way python code is presented, would it be that hard to build a list of functions based on a regex looking for def function_name(..) ?

And then search for each name and tot up how many times it features in the code. It wouldn't naturally take comments into account but as long as you're having a look at functions with less than two or three instances...

It's a bit Spartan but it sounds like a nice sleepy-weekend task =)

unless you know that your code uses reflection, as you said, I would go for a trivial grep. Do not underestimate the power of the asterisk in vim as well (performs a search of the word you have under your cursor in the file), albeit this is limited only to the file you are currently editing.

Another solution you could implement is to have a very good testsuite (seldomly happens, unfortunately) and then wrap the routine with a deprecation routine. if you get the deprecation output, it means that the routine was called, so it's still used somewhere. This works even for reflection behavior, but of course you can never be sure if you don't trigger the situation when your routine call is performed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!