首页 > 解决方案 > 在 python 包中查找某些方法和函数的所有用法

问题描述

给定一个包含某些模块的python包,我想找到包中定义的方法和函数的所有用法,我想在pycharms之类的东西中找到给定函数或方法的用法,它会显示所有行调用了这个方法/函数。

让我的包有很多模块,我想寻找. 中定义的函数和方法的用法module_x。使用inspect并且dir我可以找到定义的所有可调用对象module_x

import inspect

callables = [method_name for method_name in dir(module)
             if callable(getattr(module, method_name))]

module_inspected = inspect.getmodule(module)
module_file = module_inspected.__file__

module_x_callables = []

for name, member in inspect.getmembers(module):
    # to see if the definitions are defined/imported in the member_file that we are looking    
    if name in callables: 
        module_x_callables.append(member)
        member_file = inspect.getmodule(member).__file__
        # print('{}: {},{}'.format(name, member, callable(member)))
        print('{}'.format(name))
        print('{}'.format(member))
        #        print('parent: {}'.format(inspect.getmodule(member)))
        print('member_file: {}'.format(member_file))
        if member_file == module_file:
            source, line_no = inspect.findsource(member)
            print(line_no)
        print('\n')

注意:我认为类中的方法不会被这种方法捕获,但没关系。假设我想找到定义在module_x.

我的问题是:如何扫描包中的其他模块并查看它们是否使用了中的任何 defs module_x,如果是,请将行号返回给我。

我尝试使用ast,走树并试图找到所有的ast.Call. 这实际上重新运行了我所有的调用,但我不知道如何检查这个返回是否定义在module_x. 更重要的是,我正在考虑使用正则表达式,但例如可能test_func在两个不同的模块中调用函数。使用这种方法,我怎么知道我在打电话给哪一个?

string_code = open(file,'r').read()
tree = ast.parse(string_code)
for node in ast.walk(tree):
    #print(node)
    if isinstance(node, ast.Call):
        print('call')
        print(ast.dump(node))
        print(inspect.getmodule(node))
        print(func.value)
        print(func.attr)
        print('\n')

所以,最后,我的问题是:我怎样才能探索一个文件或一个模块,并找到所有的用法和在module_x. 谢谢 ;)

标签: python-3.xreference

解决方案


您只需要关心实际导入到您当前正在检查的模块中的名称。请注意,这里有一些并发症:

  • 导入的名称可从其他模块中导入,以从当前模块导入;import foo在模块barbar.foo可以从外部使用。所以from bar import foo真的是一回事import foo
  • 任何对象都可以存储在列表、元组中,成为另一个对象的属性,存储在字典中,分配给替代名称,并且可以动态引用。例如,存储在列表中的导入属性,由索引引用:

    import foo
    spam = [foo.bar]
    spam[0]()
    

    调用foo.bar对象。可以通过 AST 分析跟踪其中一些用途,但 Python 是一种高度动态的语言,您很快就会遇到限制。例如,您无法spam[0] = random.choice([foo.bar, foo.baz])确定会产生什么。

  • 使用globalandnonlocal语句,嵌套函数作用域可以改变父作用域中的名称。所以一个人为的功能,如:

    def bar():
        global foo
        import foo
    

    将导入模块foo并将其添加到全局命名空间,但仅在bar()被调用时。跟踪这很困难,因为您需要跟踪bar()实际调用的时间。这甚至可能发生在当前模块 ( import weirdmodule; weirdmodule.bar()) 之外。

如果您忽略这些复杂性,而只关注语句中使用的名称import,那么您需要跟踪ImportImportFrom节点,并跟踪范围(这样您就知道本地名称是否掩盖了全局名称,或者是否将导入的名称导入到本地范围)。然后查找Name(..., Load)引用导入名称的节点。

我之前已经介绍过跟踪范围,请参阅从 Python AST 获取与具有给定名称的特定变量相对应的所有节点。对于这个操作,我们可以将其简化为一堆字典(封装在一个collections.ChainMap()实例中),并添加导入:

import ast
from collections import ChainMap
from types import MappingProxyType as readonlydict


class ModuleUseCollector(ast.NodeVisitor):
    def __init__(self, modulename, package=''):
        self.modulename = modulename
        # used to resolve from ... import ... references
        self.package = package
        self.modulepackage, _, self.modulestem = modulename.rpartition('.')
        # track scope namespaces, with a mapping of imported names (bound name to original)
        # If a name references None it is used for a different purpose in that scope
        # and so masks a name in the global namespace.
        self.scopes = ChainMap()
        self.used_at = []  # list of (name, alias, line) entries

    def visit_FunctionDef(self, node):
        self.scopes = self.scopes.new_child()
        self.generic_visit(node)
        self.scopes = self.scopes.parents

    def visit_Lambda(self, node):
        # lambdas are just functions, albeit with no statements
        self.visit_Function(node)

    def visit_ClassDef(self, node):
        # class scope is a special local scope that is re-purposed to form
        # the class attributes. By using a read-only dict proxy here this code
        # we can expect an exception when a class body contains an import 
        # statement or uses names that'd mask an imported name.
        self.scopes = self.scopes.new_child(readonlydict({}))
        self.generic_visit(node)
        self.scopes = self.scopes.parents

    def visit_Import(self, node):
        self.scopes.update({
            a.asname or a.name: a.name
            for a in node.names
            if a.name == self.modulename
        })

    def visit_ImportFrom(self, node):
        # resolve relative imports; from . import <name>, from ..<name> import <name>
        source = node.module  # can be None
        if node.level:
            package = self.package
            if node.level > 1:
                # go up levels as needed
                package = '.'.join(self.package.split('.')[:-(node.level - 1)])
            source = f'{package}.{source}' if source else package
        if self.modulename == source:
            # names imported from our target module
            self.scopes.update({
                a.asname or a.name: f'{self.modulename}.{a.name}'
                for a in node.names
            })
        elif self.modulepackage and self.modulepackage == source:
            # from package import module import, where package.module is what we want
            self.scopes.update({
                a.asname or a.name: self.modulename
                for a in node.names
                if a.name == self.modulestem
            })

    def visit_Name(self, node):
        if not isinstance(node.ctx, ast.Load):
            # store or del operation, means the name is masked in the current scope
            try:
                self.scopes[node.id] = None
            except TypeError:
                # class scope, which we made read-only. These names can't mask
                # anything so just ignore these.
                pass
            return
        # find scope this name was defined in, starting at the current scope
        imported_name = self.scopes.get(node.id)
        if imported_name is None:
            return
        self.used_at.append((imported_name, node.id, node.lineno))

现在,给定模块名称foo.bar和包中模块的以下源代码文件foo

from .bar import name1 as namealias1
from foo import bar as modalias1

def loremipsum(dolor):
    return namealias1(dolor)

def sitamet():
    from foo.bar import consectetur

    modalias1 = 'something else'
    consectetur(modalias1)

class Adipiscing:
    def elit_nam(self):
        return modalias1.name2(self)

您可以解析上述内容并提取所有foo.bar引用:

>>> collector = ModuleUseCollector('foo.bar', 'foo')
>>> collector.visit(ast.parse(source))
>>> for name, alias, line in collector.used_at:
...     print(f'{name} ({alias}) used on line {line}')
...
foo.bar.name1 (namealias1) used on line 5
foo.bar.consectetur (consectetur) used on line 11
foo.bar (modalias1) used on line 15

请注意,范围中的modalias1名称sitamet不被视为对导入模块的实际引用,因为它被用作本地名称。


推荐阅读