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?
After you import the os module, then we pass the os module into the dir() function. This outputs all of the attributes and functions of the os module. This prints out all of the attributes and functions of the os module. You can see there are functions such as listdir, mkdir, makedirs, etc.
dir() is a built-in function that also returns the list of all attributes and functions in a module.
Python getattr() function. Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function.
We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With