Hi Dan,

jedi [1] or a python language server implementation (e.g. [2]) can probably help you finding all the usages of a function or class (for methods you will to have need decent typing information).

Here is a little example using jedi:

import jedi
code = '''\
class Foo:
    def used(self):
        pass

    def unused(self):
        pass

def my_func(f: Foo):
    f.used()

def my_unused_func():
    pass

def main():
    my_func(Foo())
'''
script = jedi.Script(code)

definitions = script.get_names(definitions=True)
while definitions:
    name = definitions.pop()
    if name.type == 'class':
        definitions.extend(name.defined_names())
    elif name.type == 'function':
        usages = [
            ref
for ref in script.get_references(line=name.line, column=name.column)
            if not ref.is_definition()
        ]
        print(name.full_name, "  <- UNUSED" if not usages else "")


Please note that the notion of unused code is not transitive in this example, ie. you will have to remove unused functions and run it again to see if you have new results. Also note that jedi probably cuts some corners and the results are not 100% accurate all the time.
Finally, note that this will be pretty slow on larger code bases :-)

Cheers,
Martin

[1] https://pypi.org/project/jedi/
[2] https://github.com/palantir/python-language-server

On 26.10.22 01:19, Dan Stromberg wrote:

Hello people.

Assume you have a software system that is self-contained: you do not need to concern yourself with client code that is outside that tree (because there is none, or you arbitrarily declare it unimportant as a simplifying assumption).

Is there a tool for Python that can assess whether a given function (or list of functions, method or list of methods) is used or not, within that source tree?

grep, which is what I've been using, only goes so far.  It finds comments, and it finds methods by name independent of what class they are associated with.

I have a feeling there are IDE's that do this.  These I'm interested in, but I'm a bit more interested in standalone tools apart from a GUI.

Thanks.


_______________________________________________
code-quality mailing list -- code-quality@python.org
To unsubscribe send an email to code-quality-le...@python.org
https://mail.python.org/mailman3/lists/code-quality.python.org/
Member address: mar...@vielsmaier.net

_______________________________________________
code-quality mailing list -- code-quality@python.org
To unsubscribe send an email to code-quality-le...@python.org
https://mail.python.org/mailman3/lists/code-quality.python.org/
Member address: arch...@mail-archive.com

Reply via email to