静态分析 Python 模块以查找分配
我想让我的用户编写一个像这样的 __init__.py
模块:
'''
This is the simpack's docstring.
Bla bla bla.
'''
name = 'Name of the simpack'
tags = ['list', 'of', 'simpack-tags']
__version__ = '0.9.3'
我希望我的程序能够获取所有这些内容:文档字符串、名称、标签和版本。但我想在不导入模块的情况下执行此操作,因为 __init__.py 可能会导入整个包,这可能很重。 (我想对许多重型 simpack 执行此过程。)
我们可以假设用户不会执行任何比简单的文字赋值更复杂的计算操作。
我听说 ast
模块可以做这样的事情。但是,我也希望能够对编译文件执行此过程,例如 __init__.pyc
或 __init__.pyo
,并且我不知道如何执行此操作ast
模块。
ast
模块可以对源文件和编译文件执行此操作吗?它是如何完成的?否则,还有比ast更合适的工具吗?
I want to let my users write an __init__.py
module like this:
'''
This is the simpack's docstring.
Bla bla bla.
'''
name = 'Name of the simpack'
tags = ['list', 'of', 'simpack-tags']
__version__ = '0.9.3'
And I want my program to be able to get all of these things: The docstring, the name, the tags and the version. But I want to do it without importing the module, because __init__.py
might import the entire package which can be heavy. (I want to do this process for many heavy simpacks.)
We can assume that the user doesn't do anything computationally trickier then a simple literal assignment.
I heard that the ast
module does things like this. But, I also want to be able to do this process on compiled files, e.g. __init__.pyc
or __init__.pyo
, and I don't know how to do this with the ast
module.
Can the ast
module do this on both source and compiled files? How is it done? Otherwise, is there a more fitting tool than ast
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您提出的建议听起来很困难且缺乏鲁棒性......
ast
组件可能会在您的代码中引入版本依赖性。替代方案:不要尝试分析
thepackage/__init__.py[co]?
,而是让用户编写thepackage/userconfig.py
。然后,您可以执行import thepackage.userconfig
操作,而无需导入thepackage
的全部内容What you propose smells of difficulty and lack of robustness ... the
ast
component is likely to introduce version dependencies in your code.Alternative: Instead of trying to analyse
thepackage/__init__.py[co]?
, have the users write athepackage/userconfig.py
. Then you can doimport thepackage.userconfig
without importing the whole contents ofthepackage
另一种方法是使用 2 个步骤的过程:
__init__.py
文件。此步骤由用户操作触发,例如setup.py sdist
An alternative approach is to use 2 steps process:
__init__.py
file. This step is triggered by a user action such assetup.py sdist