Statically analyzing a Python module to find assignments
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 c开发者_开发百科omputationally 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
?
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 a thepackage/userconfig.py
. Then you can do import thepackage.userconfig
without importing the whole contents of thepackage
An alternative approach is to use 2 steps process:
- generate metadata in an easy-to-read format (such as *.egg-info files) during creation of source tarballs, eggs, etc. This step imports the
__init__.py
file. This step is triggered by a user action such assetup.py sdist
- read this metadata. This step doesn't import anything. It deals only with a simple text files
精彩评论