Reputation: 20123
I need to retrieve the list of attributes of a Python module.
The catch, and this is where this question differs e.g. from this one, is that I want the list ordered according to the order they appear in the module.
As an example, consider the module
# a_module.py
b1 = 1
a0 = 1
a1 = 2
I want the list ['b1', 'a0', 'a1']
.
What I've tried:
>>> import a_module
>>> dir(a)
[..., 'a0', 'a1', 'b1']
>>> from inspect import getmembers
>>> [x[0] for x in getmembers(a_module)]
[..., 'a0', 'a1', 'b1']
Is there any way of getting the list without having to parse the file?
Upvotes: 14
Views: 728
Reputation: 37539
Yes, you will have to parse the file. You don't have to write your own parser though, you can use the ast
libary.
Using your example file
# a_module.py
b1 = 1
a0 = 1
a1 = 2
You could parse the attributes this way.
import ast
members = []
with open('file.py', 'r') as f:
src = f.read()
tree = ast.parse(src)
for child in tree.body:
if isinstance(child, ast.Assign):
for target in child.targets:
members.append(target.id)
print members
# ['b1', 'a0', 'a1']
This small script only looks at top-level attributes. It's ignoring things like imports and class and function definitions. You may have more complex logic depending on how much information you want to extract from the parsed file.
Upvotes: 4
Reputation: 746
There is no way without parsing the file.
Attribute order doesn't matter for programming unless you are trying to document. If that is your case take a look at http://www.sphinx-doc.org/
Upvotes: 0