[英]Is there a way to automatically verify all imports in a Python script without running it?
Suppose that I have a somewhat long Python script (too long to hand-audit) that contains an expensive operation, followed by a bunch of library function calls that are dependent on the output of the expensive operation. 假设我有一个有点长的Python脚本(手工审计太长),其中包含一个昂贵的操作,然后是一堆依赖于昂贵操作输出的库函数调用。
If I have not imported all the necessary modules for the library function calls, then Python will error out only after the expensive operation has finished, because Python interprets line by line. 如果我没有为库函数调用导入所有必需的模块,那么只有在昂贵的操作完成后 ,Python才会出错,因为Python会逐行解释。
Is there a way to automatically verify that I have all the necessary imports without either a) manually verifying it line by line or b) running through the expensive operation each time I miss a library? 有没有办法自动验证我有所有必要的导入没有 a)逐行手动验证它或b)每次我错过一个库时运行昂贵的操作?
Another way to put that question is whether there is a tool that will do what the C compiler does with respect to verifying dependencies before run time. 提出这个问题的另一种方法是,是否有一个工具可以执行C编译器在运行时验证依赖关系方面所做的工作。
No, this is not possible, because dependencies can be injected at runtime. 不,这是不可能的,因为可以在运行时注入依赖项。
Consider: 考虑:
def foo(break_things):
if not break_things:
globals()['bar'] = lambda: None
long_result = ...
foo(long_result > 0)
bar()
Which depending on the runtime value of long_result
, may give NameError: name 'bar' is not defined
. 根据
long_result
的运行long_result
,可能会给出NameError: name 'bar' is not defined
long_result
NameError: name 'bar' is not defined
。
There is a module called snakefood : 有一个名为snakefood的模块:
Generate dependency graphs from Python code
从Python代码生成依赖图
It uses the AST to parse the Python files.
它使用AST来解析Python文件。
This is very reliable, it always runs.
这是非常可靠的,它总是运行。 No module is loaded.
没有加载模块。 Loading modules to figure out dependencies is almost always problem, because a lot of codebases run initialization code in the global namespace, which often requires additional setup.
加载模块以确定依赖关系几乎总是问题,因为许多代码库在全局命名空间中运行初始化代码,这通常需要额外的设置。 Snakefood is guaranteed not to have this problem (it just runs, no matter what).
Snakefood保证没有这个问题(它只是运行,无论如何)。
You can get a list of imports by calling sfood-imports <script.py>
. 您可以通过调用
sfood-imports <script.py>
来获取导入列表。 Then you can import each module in the list one by one and see if it throws ImportError
. 然后,您可以逐个导入列表中的每个模块,看看它是否抛出
ImportError
。
Or, just use pylint . 或者,只使用pylint 。 Quote from docs:
从文档引用:
Error detection
错误检测
checking if declared interfaces are truly implemented
检查声明的接口是否真正实现
checking if modules are imported
检查模块是否已导入
Hope that helps. 希望有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.