python-3.x - 在 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
. 谢谢 ;)
解决方案
您只需要关心实际导入到您当前正在检查的模块中的名称。请注意,这里有一些并发症:
- 导入的名称可从其他模块中导入,以从当前模块导入;
import foo
在模块bar
中bar.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])
确定会产生什么。使用
global
andnonlocal
语句,嵌套函数作用域可以改变父作用域中的名称。所以一个人为的功能,如:def bar(): global foo import foo
将导入模块
foo
并将其添加到全局命名空间,但仅在bar()
被调用时。跟踪这很困难,因为您需要跟踪bar()
实际调用的时间。这甚至可能发生在当前模块 (import weirdmodule; weirdmodule.bar()
) 之外。
如果您忽略这些复杂性,而只关注语句中使用的名称import
,那么您需要跟踪Import
和ImportFrom
节点,并跟踪范围(这样您就知道本地名称是否掩盖了全局名称,或者是否将导入的名称导入到本地范围)。然后查找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
不被视为对导入模块的实际引用,因为它被用作本地名称。
推荐阅读
- php - 使用 str_replace 时出现多个数组错误
- python-3.x - 从 CNN 模型中获取权重和偏差并将它们保存到 csv 文件中
- r - 按特定索引对向量列表进行排序
- mongodb - 使用 Mongodb 聚合通过 id 获取对象
- python - 将 Mask_RCNN 与 jupyter notebook 一起使用时出错
- selenium - 在会话之间保留 cookie
- html - 每次有人刷新页面时如何更改文本?
- python - Twilio 仅通过 Python 从收件人那里检索消息历史记录
- haskell - 为什么这个函数不在 Haskell 中终止?
- c++ - 嵌套模板结构构造函数实现